背景
在COS上传组件中,频繁的上传大文件的情况下,临时文件夹不能及时清理,同时由于需要频繁的写入文件,上传效率大打折扣,所以需要研究流上传的内容。
原理
COS的上传组件中,写入文件的核心代码位于MultipartRequest.java中,需要改造这部分的代码,让写入文件变成写入流,得到流再处理其他事情。源代码点击此处
代码
先写个实体类,存流及其他信息。
import java.io.InputStream;
/**
* UploadStream
* @author Wilson 2018/06/27
*
*/
public class UploadStream {
private InputStream in;
private String fileName;
private String contentType;
public UploadStream(InputStream in, String filesystemName, String contentType) {
this.in = in;
this.fileName = filesystemName;
this.contentType = contentType;
}
public InputStream getInputStream() {
return in;
}
public String getFileName() {
return fileName;
}
public String getContentType() {
return contentType;
}
}
再自行写一个MultipartRequest类,重新实现应有的功能。
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import com.kxy.mapserver.util.entity.UploadStream;
import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
/**
* MultipartRequest 改造版,将文件上传改造为流上传至内存
* @author Wilson 2018/06/28
*
*/
public class MultipartRequest extends HttpServletRequestWrapper {
private List<UploadStream> uploadStreams;
public MultipartRequest(HttpServletRequest request, int maxPostSize, String encoding) {
super(request);
wrapMultipartRequest(request, maxPostSize, encoding);
}
/**
* MultipartRequest核心封装方法
* @param request http请求
* @param maxPostSize 最大上传大小
* @param encoding 字符编码
*/
private void wrapMultipartRequest(HttpServletRequest request, int maxPostSize, String encoding) {
uploadStreams = new ArrayList<UploadStream>();
try {
MultipartParser parser = new MultipartParser(request, maxPostSize, true, true, encoding);
Part part;
while ((part = parser.readNextPart()) != null) {
if (part.isFile()) {
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
//获取输入流,注意这里的输入流指针位置已经到末尾,不能再使用了,所以要借用内存流,所以不能用以下代码
//InputStream is = filePart.getInputStream();
// 写到缓存中,使用时创建InputStream进行复用
ByteArrayOutputStream baos = new ByteArrayOutputStream();
filePart.writeTo(baos);
if (fileName != null) {
uploadStreams.add(new UploadStream(new ByteArrayInputStream(baos.toByteArray()), fileName,
filePart.getContentType()));
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public List<UploadStream> getStreams() {
return uploadStreams;
}
}
最后在控制器里获取HttpServletRequest,覆盖成新的对象,返回实体对象,从中可以得到所需要的流。
if (request instanceof MultipartRequest == false)
request = new MultipartRequest(request, 1000 * 1024 * 1024, "utf-8");
List<UploadStream> uploadStreams = ((MultipartRequest)request).getStreams();
return uploadStreams.size() > 0 ? uploadStreams.get(0) : null;