接上篇
java多文件上传plupload控件实现多图片上传(一)
续写PluploadUtil 和 Plupload PO类,以及后台的action。
至此,可实现多文件上传功能。
上传文件Action类:
import gwm.xtkf.rights.domain.UserSession;
import gwm.xtkf.tool.AliyunOSSUtil;
import gwm.xtkf.tool.ResourceUtil;
import gwm.xtkf.tool.ResultMessage;
import gwm.zls.filemanage.util.Plupload;
import gwm.zls.filemanage.util.PluploadUtil;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import xs.jszx.housemanage.domain.HousePic;
import xs.jszx.housemanage.service.HousePicService;
@Controller
@RequestMapping("/housePicController")
public class HousePicController {
@Autowired
private HousePicService housePicService;
//多文件上传
@RequestMapping("/saveHousePics" )
public String saveHousePics(HousePic housePic,Plupload plupload,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IllegalStateException, IOException {
UserSession userSession = (UserSession)session.getAttribute("userSession");
plupload.setRequest(request);
//文件存储路径
String fileName = plupload.getName();
String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
String realName = UUID.randomUUID().toString() + suffix;
try {
PluploadUtil.upload2AliyunOSS(plupload, realName);
//判断文件是否上传成功(被分成块的文件是否全部上传完成)
if (PluploadUtil.isUploadFinish(plupload)) {
housePic.setRealName(realName);
housePic.setUserId(userSession.getUserId());
housePic.setCreateTime(new Date());
//写入数据库
if (this.housePicService.saveHousePic(housePic)){
return "housemanage/pic_inc/pic_houseMain";
}
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "housemanage/pic_inc/pic_houseMain";
}
PluploadUtil 类:
import gwm.xtkf.tool.AliyunOSSUtil;
import gwm.xtkf.tool.ResourceUtil;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
public class PluploadUtil {
private static final int BUF_SIZE = 2 * 1024;
/**上传失败响应的成功状态码*/
public static final String RESP_SUCCESS = "{\"jsonrpc\" : \"2.0\", \"result\" : \"success\", \"id\" : \"id\"}";
/**上传失败响应的失败状态码*/
public static final String RESP_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";
/**
* 用于Plupload插件的文件上传 到阿里OSS
* @param plupload - 存放上传所需参数的bean
* @param filename - 保存的文件名
* @throws IllegalStateException
* @throws IOException
*/
public static void upload2AliyunOSS(Plupload plupload, String filename) throws IllegalStateException, IOException {
int chunks = plupload.getChunks(); //获取总的碎片数
int chunk = plupload.getChunk(); //获取当前碎片(从0开始计数)
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) plupload.getRequest();
MultiValueMap map = multipartRequest.getMultiFileMap();
if(map != null) {
//事实上迭代器中只存在一个值,所以只需要返回一个值即可
Iterator iter = map.keySet().iterator();
while(iter.hasNext()) {
String str = (String) iter.next();
List fileList = map.get(str);
for(MultipartFile multipartFile : fileList) {
//因为只存在一个值,所以最后返回的既是第一个也是最后一个值
plupload.setMultipartFile(multipartFile);
//存储到oss上文件路径和名称
String key = ResourceUtil.getOSSHousesPic() + filename;
AliyunOSSUtil.ensureBucket();
//当chunks>1则说明当前传的文件为一块碎片,需要合并
if (chunks > 1) {
String prefix = filename.substring(0, filename.lastIndexOf(".")-1);
String suffix = filename.substring(filename.lastIndexOf("."), filename.length());
File tmpFile = File.createTempFile(prefix, suffix);
//需要创建临时文件名,最后再更改名称
//如果chunk==0,则代表第一块碎片,不需要合并
saveUploadFile(multipartFile.getInputStream(), tmpFile, chunk == 0 ? false : true);
//上传并合并完成,则将临时名称更改为指定名称
if (chunks - chunk == 1) {
AliyunOSSUtil.uploadFile(key, tmpFile);
}
} else {
AliyunOSSUtil.uploadMultipartFile(key, multipartFile);
//否则直接将文件内容拷贝至新文件
//multipartFile.transferTo(targetFile);
}
}
}
}
}
/**
* 用于Plupload插件的文件上传 上传到本地服务器
* @param plupload - 存放上传所需参数的bean
* @param dir - 保存目标文件目录
* @throws IllegalStateException
* @throws IOException
*/
public static void upload2Local(Plupload plupload, String filePath, String fileName) throws IllegalStateException, IOException {
int chunks = plupload.getChunks(); //获取总的碎片数
int chunk = plupload.getChunk(); //获取当前碎片(从0开始计数)
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) plupload.getRequest();
MultiValueMap map = multipartRequest.getMultiFileMap();
if(map != null) {
File dir = new File(filePath);
if (!dir.exists()) dir.mkdirs(); //如果目标文件夹不存在则创建新的文件夹
//事实上迭代器中只存在一个值,所以只需要返回一个值即可
Iterator iter = map.keySet().iterator();
while(iter.hasNext()) {
String str = (String) iter.next();
List fileList = map.get(str);
for(MultipartFile multipartFile : fileList) {
//因为只存在一个值,所以最后返回的既是第一个也是最后一个值
plupload.setMultipartFile(multipartFile);
//创建新目标文件
File targetFile = new File(dir.getPath()+ "/" + fileName);
//当chunks>1则说明当前传的文件为一块碎片,需要合并
if (chunks > 1) {
//需要创建临时文件名,最后再更改名称
File tempFile = new File(dir.getPath()+ "/" + multipartFile.getName());
//如果chunk==0,则代表第一块碎片,不需要合并
saveUploadFile(multipartFile.getInputStream(), tempFile, chunk == 0 ? false : true);
//上传并合并完成,则将临时名称更改为指定名称
if (chunks - chunk == 1) {
tempFile.renameTo(targetFile);
}
} else {
//否则直接将文件内容拷贝至新文件
multipartFile.transferTo(targetFile);
}
}
}
}
}
/**
* 保存上传文件,兼合并功能
*/
private static void saveUploadFile(InputStream input, File targetFile, boolean append) throws IOException {
OutputStream out = null;
try {
if (targetFile.exists() && append) {
out = new BufferedOutputStream(new FileOutputStream(targetFile, true), BUF_SIZE);
} else {
out = new BufferedOutputStream(new FileOutputStream(targetFile), BUF_SIZE);
}
byte[] buffer = new byte[BUF_SIZE];
int len = 0;
//写入文件
while ((len = input.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
throw e;
} finally {
//关闭输入输出流
if (null != input) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 判断是否全部上传完成
* 碎片需合并后才返回真
*/
public static boolean isUploadFinish(Plupload plupload) {
return (plupload.getChunks() - plupload.getChunk() == 1);
}
}
Plupload PO类:
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
/**
* Plupload是一个上传插件。
* 这是一个bean类,主要存储Plupload插件上传时需要的参数。
* 属性名不可随意改动.
* 这里主要使用MultipartFile文件上传方法
*/
public class Plupload {
/**文件临时名(打文件被分解时)或原名*/
private String name;
/**总的块数*/
private int chunks = -1;
/**当前块数(从0开始计数)*/
private int chunk = -1;
/**HttpServletRequest对象,不能直接传入进来,需要手动传入*/
private HttpServletRequest request;
/**保存文件上传信息,不能直接传入进来,需要手动传入*/
private MultipartFile multipartFile;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChunks() {
return chunks;
}
public void setChunks(int chunks) {
this.chunks = chunks;
}
public int getChunk() {
return chunk;
}
public void setChunk(int chunk) {
this.chunk = chunk;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public MultipartFile getMultipartFile() {
return multipartFile;
}
public void setMultipartFile(MultipartFile multipartFile) {
this.multipartFile = multipartFile;
}
}