在java项目中常用的上传文件的方式为:通过提交form表单的形式进行文件提交,但这样进行提交的一个不好之处是不好对提交成功或失败之后在前台进行逻辑处理。因此在这里使用ajaxfileupload.js提供的一种上传文件的方式进行文件文件提交,该种上传文件的方式为异步提交,且便于前台对后台处理的结果做出反应。
ajaxfileupload.js上传文件的方法为:
$.ajaxFileUpload({
data:{"name":"张三"},//除文件以外的其他参数
url: '',//文件接收地址
secureuri: true,//是否安全提交
fileElementId: 'input',//上传控件ID
dataType: 'json',//返回的数据信息格式
success: function(data) {//上传成功回调函数 },
error: function(data) {//上传失败回调函数 } }) <input type="file" name="data" value="" id="input">//需要特别注意:name属性的值不能少,否则后台接收只能接收到参数而不能接收到文件。
java服务器端的代码(在文件接收中需要用到的jar包:commons-fileupload-1.3.jar commons-io-2.4.jar servlet-api.jar):
String savePath = "E:/szgasfile/uploadanddown/image";//文件存放目录
String tempPath = "E:/szgasfile/uploadanddown/temp";//缓存目录
File tmpFile = new File(tempPath);
if (!tmpFile.exists()) {
tmpFile.mkdir();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024);//设置缓冲区的大小为1MB,如果不指定,那么缓冲区的大小默认是10KB
factory.setRepository(tmpFile);
//创建一个文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setProgressListener(new ProgressListener(){ //文件上传监听器
public void update(long pBytesRead, long pContentLength, int arg2) {
System.out.println("文件大小为:" + pContentLength/1024 + ",当前已处理:" + pBytesRead/1024);
}
});
// if(!ServletFileUpload.isMultipartContent(request)){
// //按照传统方式获取数据
// }
upload.setFileSizeMax(1024*1024*50);
upload.setSizeMax(1024*1024*10*1024);
List<FileItem> list = upload.parseRequest(request);
InputStream in=null;
FileOutputStream out=null;
for(FileItem item : list){//遍历每一个文件
if(item.isFormField()){ //获取上传文件时上传的字段信息
String name = item.getFieldName();//key
String value = item.getString("UTF-8");//value
}else{
String filename = item.getName();
if(filename==null || filename.trim().equals("")){
continue;
}
in = item.getInputStream();
String uuid=UUID.randomUUID().toString().replace("-", "");
String newPicName=uuid+"_"+filename;
out = new FileOutputStream(savePath + "\\" + newPicName);
byte buffer[] = new byte[1024];
int len = 0;
while((len=in.read(buffer))>0){ //将文件写入指定路径
out.write(buffer, 0, len);
}
}
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}