文件流式上传
2019-05-10 21:11:57
820次阅读
0个评论
和传统API不一样的是,传统API中文件在被用户读取前,必须等待被保存在内存或者硬盘中(临时文件),这种方法非常简单,但是另一方面却带来了内存和时间上的额外开销。流式API更佳轻量级,它可以让你牺牲一点便利性以换得理想的性能,文件可以直接从网络输入流中获取。
@RequestMapping("/test3")
public void test3() throws Exception {
HttpServletRequest httpServletRequest = getHttpServletRequest();
HttpServletResponse httpServletResponse = getHttpServletResponse();
//过程监听器
ProgressListener progressListener = new ProgressListener() {
/**
* @param pBytesRead 已经读取的字节数
* @param pContentLength 总字节数
* @param pItems 字段编号
*/
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("已读取字节:" + pBytesRead);
System.out.println("总字节:" + pContentLength);
System.out.println("字段编号:" + pItems);
}
};
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
//设置允许上传的单个文件最大尺寸,单位字节
servletFileUpload.setFileSizeMax(1024 * 1024 * 1024 * 10l);
//设置整个请求的大小的最大值,单位字节
servletFileUpload.setSizeMax(1024 * 1024 * 1024 * 100l);
//设置过程监听器
servletFileUpload.setProgressListener(progressListener);
boolean isMultipartContent = servletFileUpload.isMultipartContent(httpServletRequest);
if (isMultipartContent) {
//开始上传文件并解析请求,按顺序获取各个表单项
FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);
while (fileItemIterator.hasNext()) {
FileItemStream fileItemStream = fileItemIterator.next();
String name = fileItemStream.getFieldName();
if (fileItemStream.isFormField()) {
try (InputStream inputStream = fileItemStream.openStream()) {
System.out.println("表单字段:" + name + ",值:"
+ Streams.asString(inputStream, "utf-8"));
}
} else {
System.out.println("原始文件名:" + fileItemStream.getName());
System.out.println("MIME类型:" + fileItemStream.getContentType());
try (
//文件输出流
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("d:/" + fileItemStream.getName()));
//文件输入流
InputStream inputStream = new BufferedInputStream(fileItemStream.openStream());) {
byte[] bytes = new byte[1024 * 8];
int n;
while (-1 != (n = inputStream.read(bytes))) {
bufferedOutputStream.write(bytes, 0, n);
}
}
}
}
}
try (PrintWriter printWriter = httpServletResponse.getWriter()) {
httpServletResponse.setContentType("text/html; charset=utf-8");
printWriter.println("<script>alert('上传成功');</script>");
}
}
00
相关话题
- SpringMVC流式上传文件
- SpringMVC使用StandardServletMultipartResolver上传文件
- SpringBoot设置上传文件大小
- Ajax跨域上传文件
- Servlet3.0原生API文件上传
- SpringMVC 配置servlet3.0 文件上传
- javascript判断上传的文件是否为图片
- 使用jquery-form.js异步上传文件
- Nginx 上传文件出现413 Request Entity Too Large错误
- Apache的commons-net实现FTP的文件上传下载
- 前端图片压缩与上传OSS组件
- h5调用摄像头实现拍照上传
- Nginx支持字体文件
- Spring MVC 文件下载
- Javacsv读写csv文件