由于业务需求,要将图片上传到服务器,所以用了百度的webuploader。
webuploader主要用于js页面前台实现,不关注后台,后台还要自己写。
前台页面upImage.jsp
"en">
"Content-Type" content="text/html;charset=UTF-8">
"stylesheet" type="text/css" href="../css/webuploader.css" />
"stylesheet" type="text/css" href="../css/style.css" />
"text">0%
"percentage">
主要要引进4个JS页面和2个css页面
调用连接的配置主要是在
upload.js里面的WebUploader.create里面,如下:
//读取当前系统的路径例如本地的话就是http://localhost:8080
var basePath=window.location.protocol+ "//"+window.location.host;
// 实例化
uploader = WebUploader.create({
pick: {
id: '#filePicker',
label: '点击选择文件'
},
formData: {
uid: 123
},
dnd: '#dndArea',
paste: '#uploader',
swf: '../js/Uploader.swf',
chunked: true,
chunkSize: 512 * 1024,
//调用的链接主要在这里配置
server: basePath+'/SunImageUpload/UpImage/upload1.do',
//server: 'http://localhost:8080/SunImageUpload/UpImage/upload1.do',
method:'POST',
// runtimeOrder: 'flash',
// accept: {
// title: 'Images',
// extensions: 'gif,jpg,jpeg,bmp,png',
// mimeTypes: 'image/*'
// },
// 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。
disableGlobalDnd: true,
fileNumLimit: 300,
fileSizeLimit: 2000 * 1024 * 1024, // 200 M
fileSingleSizeLimit: 500 * 1024 * 1024 // 50 M
});
后台接受java文件UpImageController.java如下
package com.sunyard.insurance.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.math.NumberUtils;
@Controller
@RequestMapping("/UpImage")
public class UpImageController {
@SuppressWarnings("unchecked")
@RequestMapping(value = "/upload", method = { RequestMethod.POST,RequestMethod.GET })
@ResponseBody
public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception{
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 得到所有的表单域,它们目前都被当作FileItem
List
String id = "";
String fileName = "";
// 如果大于1说明是分片处理
int chunks = 1;
int chunk = 0;
FileItem tempFileItem = null;
for (FileItem fileItem : fileItems) {
if (fileItem.getFieldName().equals("id")) {
id = fileItem.getString();
} else if (fileItem.getFieldName().equals("name")) {
fileName = new String(fileItem.getString().getBytes("ISO-8859-1"), "UTF-8");
} else if (fileItem.getFieldName().equals("chunks")) {
chunks = NumberUtils.toInt(fileItem.getString());
} else if (fileItem.getFieldName().equals("chunk")) {
chunk = NumberUtils.toInt(fileItem.getString());
} else if (fileItem.getFieldName().equals("file")) {
tempFileItem = fileItem;
}
}
// 临时目录用来存放所有分片文件
String tempFileDir = getTempFilePath() + File.separator + id;
File parentFileDir = new File(tempFileDir);
if (!parentFileDir.exists()) {
parentFileDir.mkdirs();
}
// 分片处理时,前台会多次调用上传接口,每次都会上传文件的一部分到后台(默认每片为5M)
File tempPartFile = new File(parentFileDir, fileName + "_" + chunk+ ".part");
FileUtils.copyInputStreamToFile(tempFileItem.getInputStream(),
tempPartFile);
// 是否全部上传完成
// 所有分片都存在才说明整个文件上传完成
boolean uploadDone = true;
for (int i = 0; i < chunks; i++) {
File partFile = new File(parentFileDir, fileName + "_" + i
+ ".part");
if (!partFile.exists()) {
uploadDone = false;
}
}
// 所有分片文件都上传完成
// 将所有分片文件合并到一个文件中
if (uploadDone) {
File destTempFile = new File(getTempFilePath(), fileName);
for (int i = 0; i < chunks; i++) {
File partFile = new File(parentFileDir, fileName + "_"
+ i + ".part");
FileOutputStream destTempfos = new FileOutputStream(destTempFile, true);
FileUtils.copyFile(partFile, destTempfos);
destTempfos.close();
}
// 得到 destTempFile 就是最终的文件
// 添加到文件系统或者存储中
// 删除临时目录中的分片文件
//FileUtils.deleteDirectory(parentFileDir);
// 删除临时文件
//destTempFile.delete();
} else {
// 临时文件创建失败
if (chunk == chunks -1) {
FileUtils.deleteDirectory(parentFileDir);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
@RequestMapping(value = "/upload1", method = { RequestMethod.POST,RequestMethod.GET })
@ResponseBody
public void upload1(HttpServletRequest request, HttpServletResponse response) throws Exception{
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 得到所有的表单域,它们目前都被当作FileItem
List
String fileName = "";
FileItem tempFileItem = null;
for (FileItem fileItem : fileItems) {
if (fileItem.getFieldName().equals("name")) {
fileName = new String(fileItem.getString().getBytes("ISO-8859-1"), "UTF-8");
} else if (fileItem.getFieldName().equals("file")) {
tempFileItem = fileItem;
}
}
File destTempFile = new File(getTempFilePath(), fileName);
FileUtils.copyInputStreamToFile(tempFileItem.getInputStream(),
destTempFile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String getTempFilePath() {
// TODO Auto-generated method stub
return "/Applications/yhb/123";
}
}
其中upload方法是分段读取,如一个图片文件过大,可以分段读取,一次读取5M
upload1方法是直接传输。
注:如果传多张图片,则会多次调用upload1方法,比如前台传输两张图片,upload1方法就会调用两次
上传之后保存路径在getTempFilePath方法里面配置
由于是maven文件,jar包直接在pom.xml里面配置