">java进行文件上传,带进度条varover=false;varinter;function" />
先看看效果:
JSP页面:upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
var over = false;
var inter;
function upload(){
over = false;
$("#state").html("")
$("#progress").css("width","0")
$("input[type=submit]").attr("disabled",true);
$("#progress").css("width","0%");
$("#state").html("正在上传... 总大小:0MB,已上传:0MB,0%,已用时:0秒,剩余时间:0秒,速度:0KB/S");
inter = setInterval(req,1000);
}
function req(){
//如果上传已经完成
if(over){
clearInterval(inter);
return;
}
var url = "upload/AjaxServlet";
$.get(url,function(date){
var state = date.split("-");
$("#state").html("正在上传... 总大小:"+state[4]+"MB,已上传:"+state[3]+"MB,"+state[2]+"%,已用时:"+state[0]+"秒,剩余时间:"+state[5]+"秒,速度:
"+state[1]+"KB/S");
$("#progress").animate({width:state[2]+"%"},500);
if(state[3] == state[4]){
over = true;
$("input[type=submit]").attr("disabled",false);
$("#state").html("上传已完成,总大小:"+state[4]+"MB,已上传:"+state[3]+"MB,"+state[2]+"%,已用时:"+state[0]+"秒,剩余时间:"+state[5]+"秒,速度:"+state[1]+"KB/S");
}
});
}
Servlet:
AjaxServlet.java
package com.hongfei.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hongfei.entity.Upload;
@SuppressWarnings("serial")
public class AjaxServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public AjaxServlet() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Cache-Control", "no-store");// 禁止浏览器缓存
response.setHeader("Pragrma", "no-cache");// 禁止浏览器缓存
response.setDateHeader("Expires", 0);// 禁止浏览器缓存
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Upload upload = null;
upload = (Upload)request.getSession().getAttribute("upload");
if(null == upload)
return;
long currentTime = System.currentTimeMillis();
//计算已用时,以S为单位
long time = (currentTime - upload.getStartTime()) / 1000 + 1;
//计算速度,以kb为单位
long speed = (long)(double)upload.getUploadSize() / 1024 / time;
//计算百分比
int percent = (int)((double)upload.getUploadSize() / (double)upload.getTotalSize() * 100);
//已经完成
int mb = (int)upload.getUploadSize() / 1024 / 1024;
//总共有多少
int totalMb = (int)upload.getTotalSize() / 1024 / 1024;
//剩余时间
int shenYu = (int)((upload.getTotalSize() - upload.getUploadSize()) / 1024 / speed);
String str = time+"-"+speed+"-"+percent+"-"+mb+"-"+totalMb+"-"+shenYu;
out.print(str);
out.flush();
out.close();
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("");
out.println("");
out.println("
out.println("
");out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" ");
out.println("");
out.flush();
out.close();
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
Upload.java
package com.hongfei.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import https://www.sodocs.net/doc/f79044460.html,mons.fileupload.FileItem;
import https://www.sodocs.net/doc/f79044460.html,mons.fileupload.FileUploadException; import https://www.sodocs.net/doc/f79044460.html,mons.fileupload.disk.DiskFileItemFactory; import https://www.sodocs.net/doc/f79044460.html,mons.fileupload.servlet.ServletFileUpload;
import com.hongfei.lister.UploadLister;
@SuppressWarnings("serial")
public class Upload extends HttpServlet {
/**
* Constructor of the object.
*/
public Upload() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("");
out.println("");
out.println("
out.println("
");out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" ");
out.println("");
out.flush();
out.close();
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@SuppressWarnings({ "deprecation", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
com.hongfei.entity.Upload upload = new com.hongfei.entity.Upload();
UploadLister lister = new UploadLister(upload);
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
//只是上传监听器
servletFileUpload.setProgressListener(lister);
request.getSession().setAttribute("upload", upload);
List list = null;
try {
list = servletFileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
for(Iterator iter = list.iterator(); iter.hasNext();){
//得到文件对象
FileItem fileItem = (FileItem)iter.next();
//是表单才进行处理
if(fileItem.isFormField()){
break;
}
//同意linux和windows的路径分隔符
String name = fileItem.getName().replaceAll("/", "\\");
//得到文件名
int index = https://www.sodocs.net/doc/f79044460.html,stIndexOf("\\");
String fileFileName = "";
if(index == -1){
fileFileName = name;
}else{
fileFileName = name.substring(index + 1);
}
InputStream fileInputStream = fileItem.getInputStream();
String path = request.getRealPath("/upload");
//也可不用自己写实现方法直接使用,fileItem.write(uploadFile);
File uploadFile = new File(path,fileFileName);
//首先要确认路径是否存在
uploadFile.getParentFile().mkdirs();
//检查文件是否已经存在
if(!uploadFile.exists()){
//建立文件
uploadFile.createNewFile();
}
FileOutputStream out2 = new FileOutputStream(uploadFile);
//开始copy文件
@SuppressWarnings("unused")
int len = 0;//每次读取的字节数
byte[] bytes = new byte[1024];
while((len = fileInputStream.read(bytes, 0, bytes.length)) != -1){ out2.write(bytes);
}
out2.flush();
out2.close();
fileInputStream.close();
}
out.flush();
out.close();
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
Lister:监听
UploadLister.java
package com.hongfei.lister;
import https://www.sodocs.net/doc/f79044460.html,mons.fileupload.ProgressListener;
import com.hongfei.entity.Upload;
public class UploadLister implements ProgressListener{
private Upload upload = null;
public UploadLister(Upload upload){
this.upload = upload;
}
public void update(long uploadSize,long totalSize,int items) {
upload.setUploadSize(uploadSize);
upload.setTotalSize(totalSize);
}
}
Upload.java
package com.hongfei.entity;
public class Upload {
private long totalSize; //总大小private long startTime = System.currentTimeMillis(); //开始时间
private long uploadSize; //已上传的大小public long getTotalSize() {
return totalSize;
}
public void setTotalSize(long totalSize) {
this.totalSize = totalSize;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getUploadSize() {
return uploadSize;
}
public void setUploadSize(long uploadSize) {
this.uploadSize = uploadSize;
}
}
Web.xml
xmlns="https://www.sodocs.net/doc/f79044460.html,/xml/ns/javaee" xmlns:xsi="https://www.sodocs.net/doc/f79044460.html,/2001/XMLSchema-instance" xsi:schemaLocation="https://www.sodocs.net/doc/f79044460.html,/xml/ns/javaee https://www.sodocs.net/doc/f79044460.html,/xml/ns/javaee/web-app_2_5.xsd">
需要的JS:
需要jar包:
PS:需要源代码工程文件的可以找我!!!很实用的java带进度条的上传文件:
在Struts 2中实现文件上传 前一阵子有些朋友在电子邮件中问关于Struts 2实现文件上传的问题,所以今天我们就来讨论一下这个问题。 实现原理 Struts 2是通过Commons FileUpload文件上传。Commons FileUpload通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。从而我们就能够以本地文件方式的操作浏览器上传的文件。 具体实现 前段时间Apache发布了Struts 2.0.6 GA,所以本文的实现是以该版本的Struts 作为框架的。以下是例子所依赖类包的列表: 清单1 依赖类包的列表 首先,创建文件上传页面FileUpload.jsp,内容如下: <% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncodi ng = " utf-8 " %> <% @ taglib prefix = " s " uri = " /struts-tags " %>
PHP 文件上传进度条实现程序 在php中要实现上传进度条有很多方法,如ajax是现在的主流或利用iframe来实现,现在我们来介绍php的apc与uploadprogress实现文件上传进度条效果。 目前我知道的方法有两种,一种是使用PHP的创始人Rasmus Lerdorf 写的APC扩展模块来实现(https://www.sodocs.net/doc/f79044460.html,/package/apc),另外一种方法是使用PECL扩展模块 uploadprogress实现(https://www.sodocs.net/doc/f79044460.html,/package/uploadprogress)我这里举两个分别实现的例子供参考,更灵活的应用根据自己需要来修改。 APC实现方法: 安装APC,参照官方文档安装,可以使用PECL模块安装方法快速简捷,这里不说明 配置php.ini,设置参数apc.rfc1867=1 ,使APC支持上传进度条功能,在APC源码说明文档里面有说明 代码范例: 代码如下复制代码if ($_SERVER['REQUEST_METHOD'] == 'POST') { //上传请求 $status = apc_fetch('upload_' . $_POST['APC_UPLOAD_PROGRESS']); $status['done'] = 1; echo json_encode($status); //输出给用户端页面里的ajax调用,相关文档请自己寻找exit; } elseif (isset($_GET['progress_key'])) { //读取上传进度 $status = apc_fetch('upload_'.$_GET['progress_key']); echo json_encode($status);
视频网站中提供的在线视频播放功能,播放的都是FLV格式的文件,它是Flash动画文件,可通过Flash 制作的播放器来播放该文件.项目中用制作的播放器. 多媒体视频处理工具FFmpeg有非常强大的功能包括视频采集功能、视频格式转换、视频抓图、给视频加水印等。?? ffmpeg视频采集功能非常强大,不仅可以采集视频采集卡或USB摄像头的图像,还可以进行屏幕录制,同时还支持以RTP方式将视频流传送给支持RTSP的流媒体服务器,支持直播应用。 1.能支持的格式 ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等) 2.不能支持的格式 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),可以先用别的工具(mencoder)转换为avi(ffmpeg 能解析的)格式. 实例是将上传视频转码为flv格式,该格式ffmpeg支持,所以我们实例中需要ffmpeg视频处理工具. 数据库 实例所需要的数据库脚本 drop database if exists db_mediaplayer;create database db_mediaplayer;use db_mediaplayer; create table tb_media( id int not null primary key auto_increment comment '主键' , title varchar(50) not null comment '视频名称' , src varchar(200) not null comment '视频存放地址' , picture varchar(200) not null comment '视频截图' , descript varchar(400) comment '视频描述' , uptime varchar(40) comment '上传时间' );
jsp中实现一个页面纯io流上传文件 <%@ page language="java" import="java.util.*" pageEncoding="gb2312"%> <%@page import="java.io.*"%> <%@page import="java.sql.*"%>
? 一个通用的Java文件上传类,支持上传图片,支持生成缩略图,设置最大上传文件字节数,不设置时默认10M,可接收来自表单的数据,当有多个文件域时, 只上传有文件的,忽略其他不是文件域的所有表单信息,支持用户对上传文件大小, 字节进行设置,本上传类可过滤掉以下文件类型:".exe", ".com", ".cgi", ".asp", ".php", ".jsp"等,你可自已添加过滤的文件后缀,上传文件时如果没有上传目录,则自动创建它。。。 ? package com.gootrip.util; import java.io.File; import java.util.*; import https://www.sodocs.net/doc/f79044460.html,mons.fileupload.*; import javax.servlet.http.HttpServletRequest; import java.util.regex.Pattern; import java.io.IOException; import https://www.sodocs.net/doc/f79044460.html,mons.fileupload.servlet.ServletFileUpload; import https://www.sodocs.net/doc/f79044460.html,mons.fileupload.disk.DiskFileItemFactory; import java.util.regex.Matcher; /** * TODO 要更改此生成的类型注释的模板,请转至 * 窗口-首选项- Java -代码样式-代码模板 */ public class FileUploadUtil {
//当上传文件超过限制时设定的临时文件位置,注意是绝对路径 private String tempPath = null; //文件上传目标目录,注意是绝对路径 private String dstPath = null; //新文件名称,不设置时默认为原文件名 private String newFileName = null; //获取的上传请求 private HttpServletRequest fileuploadReq = null; //设置最多只允许在内存中存储的数据,单位:字节,这个参数不要设置太大 private int sizeThreshold = 4096; //设置允许用户上传文件大小,单位:字节 //共10M private long sizeMax = 10485760; //图片文件序号 private int picSeqNo = 1; private boolean isSmallPic = false; public FileUploadUtil(){ } public FileUploadUtil(String tempPath, String destinationPath){ this.tempPath = tempPath; this.dstPath = destinationPath; }
java中几种上传方法介绍、比较 1引言 一个网站总是不可避免的要和用户进行信息的交互,能直接使用 request.getParameter()来取得。至于所使用的方法有很多种,比如:jspsmart 公司的jspsmartupload组件,O`Rrilly公司的cos组件,Jakarta Apache公司的commonsFileUpload组件,JavaZoom的uploadbean组件,还有Struts组件中自带的org.apache.struts.upload类工具等等。下面就针对其中的三种解决方案(jspsmartupload、O`Reilly-cos、struts.upload)做一个简单的介绍和对比。2O`Rrilly-Cos Cos组件是O`Rrilly公司开发的,该组件免费,不定期增加新功能,开源。 图1O`Rrilly-Cos 在Cos组件中,MultipartRequest类主要负责文件上传的处理。MultipartRequest有8个构造函数: 1.Public MultipartRequest(HttpServletRequest request,String saveDirectory,)throws IOException 2.Public MultipartRequest(HttpServletRequest request,String saveDirectory,int maxPostSize)throws IOException 3.Public MultipartRequest(HttpServletRequest request,String saveDirectory,int maxPostSize,FileRenamePolicy policy)throws IOException倘若是从窗体传送一般的简单输入类型(例如:text、password、radio、checkbox、select等等)的信息到服务器端时,只要使用 application/x-www-form-urlencoded的编码方式用session传递就可以了。但是当涉及到和用户之间的文件交换(包括上传和下载)时,就不是那么简单了。在上传文件到服务器时,必须要使用multipart/form-data的编码方式,并且不
特点: 1.可以多文件上传; 2.返回上传后的文件名; 3.form表单中的其他参数也可以得到。先贴上传类,JspFileUpload package com.vogoal.util; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; /* * vogoalAPI 1.0 * Auther SinNeR@https://www.sodocs.net/doc/f79044460.html, * by https://www.sodocs.net/doc/f79044460.html, * mail: vogoals@hotm https://www.sodocs.net/doc/f79044460.html, */ /** * JSP上传文件类 * * @author SinNeR * @version 1.0 */ public class JspFileUpload { /** request对象*/
private HttpServletRequest request = null; /** 上传文件的路径*/ private String uploadPath = null; /** 每次读取得字节的大小*/ private static int BUFSIZE = 1024 * 8; /** 存储参数的Hashtable */ private Hashtable paramHt = new Hasptable(); /** 存储上传的文件的文件名的ArrayList */ private ArrayList updFileArr = new ArrayList(); /** * 设定request对象。 * * @param request * HttpServletRequest request对象 */ public void setRequest(HttpServletRequest request) { this.request = request; } /** * 设定文件上传路径。 * * @param path * 用户指定的文件的上传路径。 */ public void setUploadPath(String path) { this.uploadPath = path; } /** * 文件上传处理主程序。 �������B * * @return int 操作结果0 文件操作成功;1 request对象不存在。2 没有设定文件保存路径或者
package com.lsl.util; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; /** * * @author Administrator * 图像处理类 */ public class PicCompression { /** * 压缩图片方法 * * @param oldFile * 将要压缩的图片的绝对地址 * @param width * 压缩宽 * @param height * 压缩长 * @param quality * 压缩清晰度建议为1.0 * @param smallIcon * 压缩图片后,添加的扩展名 * @return */ public String zoom(String oldFile, int width, int height, float quality) { if (oldFile == null) { return null; } String newImage = null; try { File file = new File(oldFile);
tomcat上传文件下载文件 首先介绍一下我们需要的环境:我用的是myeclipse8.5的java开发环境,tomcat是用的apache-tomcat-6.0.26这个版本。首先先需要准备一下使用到的 jar包 这些jar包是struts2的jar包。这些jar包是都是用于上传文件的。 注意:这里的jar包版本必须是对应的,如不是可能会tomcat下报错。所以大家最好注意一下啊。最好是用这套jar包。我将会在csdn上将项目jar包发上去。 Jar下载地址(0 分):https://www.sodocs.net/doc/f79044460.html,/detail/woaixinxin123/4193113 源代码下载(10分): https://www.sodocs.net/doc/f79044460.html,/detail/woaixinxin123/4193134 开始搭建我们的项目。创建web项目名字为File。 第一步:搭建struts2框架。 1、到jar包。
2、编辑web.xml
using System; using System.Collections.Generic; using https://www.sodocs.net/doc/f79044460.html,ponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace文件的上传原理_练习使用进度条_ { public partial class Form1 : Form { string path;//选择文件的路径 string fName;//要上传的文件的名字 public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { progressBar1.Visible = false; label2.Visible = false; } private void btnLiulan_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); fName = openFileDialog1.SafeFileName.ToString();
textBox1.Text = fName; path = openFileDialog1.FileName.ToString(); path = path.Remove(path.Length - fName.Length); } private void btnStartDownload_Click(object sender, EventArgs e) { int length = 0; int speed; DirectoryInfo di = new DirectoryInfo(path); FileInfo[] fi = di.GetFiles(); foreach (FileInfo fi1 in fi) { if (fName == fi1.ToString()) { length = (int)(fi1.Length); break; } } speed = length / 1024; progressBar1.Maximum = (length / 1024)*100; progressBar1.Value = 0; progressBar1.Step = speed; label2.Visible = true; progressBar1.Visible = true; for (int i = 0; i < (length / 1024) * 100; i += speed) { progressBar1.Value += speed; //label2.Text = "速度:" + speed + "KB/s"; System.Threading.Thread.Sleep(100); } } } }
Java实现视频网站的视频上传、视频转码、视频关键帧抽图, 及视频播放功能 视频网站中提供的在线视频播放功能,播放的都是FLV格式的文件,它是Flash动画文件,可通过Flash制作的播放器来播放该文件.项目中用制作的播放器. 多媒体视频处理工具FFmpeg有非常强大的功能包括视频采集功能、视频格式转换、视频抓图、给视频加水印等。?? ffmpeg视频采集功能非常强大,不仅可以采集视频采集卡或USB摄像头的图像,还可以进行屏幕录制,同时还支持以RTP方式将视频流传送给支持RTSP的流媒体服务器,支持直播应用。 1.能支持的格式 ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等) 2.不能支持的格式 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式. 实例是将上传视频转码为flv格式,该格式ffmpeg支持,所以我们实例中需要ffmpeg视频处理工具. 数据库 实例所需要的数据库脚本 drop database if exists db_mediaplayer;create database db_mediaplayer;use db_mediaplayer; create table tb_media( id int not null primary key auto_increment comment '主键' , title varchar(50) not null comment '视频名称' , src varchar(200) not null comment '视频存放地址' , picture varchar(200) not null comment '视频截图' , descript varchar(400) comment '视频描述' , uptime varchar(40) comment '上传时间' ); desc tb_media;
Web大文件分片上传 Web环境中大文件上传不能再用form表单一次上传了,这样效率太低; 我在不断尝试SpringMVC环境下分片接受文件,最终失败;原因目测是SpringMVC、Struts 框架是不支持HTML5方式上传的(这类框架只能支持Form表单方式的文件上传,或者FLash) 那我们可以使用Servlet和SpringMVC结合集成方式实现大文件分片上传; 一、来看看我们的web.xml的配置 很明显两个servlet,上面一个配置的是SpringMVC的入口,下面servlet是视频上传; 他们俩的url-pattern不能冲突;
二、先来看看WebUploader的前端代码 以下是代码: <%@page language="java"contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>