File upload (Upload)
The WebMVC module is very simple for file upload processing and uploaded file operations. It can be easily done through annotations:
@FileUpload: declare controller method requirements Process the uploaded file stream;
has no parameters. It should be noted that the form enctype attribute for file upload processing:
<form action="/demo/upload" method="POST" enctype="multipart/form-data"> ...... </form>
IUploadFileWrapper: Upload file wrapper interface, providing a series of methods to operate uploaded files;
Sample code:
@Controller @RequestMapping("/demo) public class UploadController { // 处理单文件上传 @RequestMapping(value = "/upload", method = Type.HttpMethod.POST) @FileUpload public IView doUpload(@RequestParam IUploadFileWrapper file) throws Exception { // 获取文件名称 file.getName(); // 获取文件大小 file.getSize(); // 获取完整的文件名及路径 file.getPath(); // 获取文件Content-Type file.getContentType(); // 转移文件 file.transferTo(new File("/temp", file.getName())); // 保存文件 file.writeTo(new File("/temp", file.getName()); // 删除文件 file.delete(); // 获取文件输入流对象 file.getInputStream(); // 获取文件输出流对象 file.getOutputStream(); return View.nullView(); } // 处理多文件上传 @RequestMapping(value = "/uploads", method = Type.HttpMethod.POST) @FileUpload public IView doUpload(@RequestParam IUploadFileWrapper[] files) throws Exception { // ...... return View.nullView(); } }
File upload related configuration parameters:
#------------------------------------- # 文件上传配置参数 #------------------------------------- # 文件上传临时目录,为空则默认使用:System.getProperty("java.io.tmpdir") ymp.configs.webmvc.upload_temp_dir= # 上传文件大小最大值(字节),默认值:-1(注:10485760 = 10M) ymp.configs.webmvc.upload_file_size_max= # 上传文件总量大小最大值(字节), 默认值:-1(注:10485760 = 10M) ymp.configs.webmvc.upload_total_size_max= # 内存缓冲区的大小,默认值: 10240字节(=10K),即如果文件大于10K,将使用临时文件缓存上传文件 ymp.configs.webmvc.upload_size_threshold= # 文件上传状态监听器,可选参数,默认值为空 ymp.configs.webmvc.upload_file_listener_class=
File upload status listener (upload_file_listener_class) configuration:
The file upload of the WebMVC module is implemented based on the Apache Commons FileUpload component, so the monitoring of the file upload status can be realized through the ProgressListener interface provided by itself;
Sample code: realize the progress calculation of the uploaded file;
public class UploadProgressListener implements ProgressListener { public void update(long pBytesRead, long pContentLength, int pItems) { if (pContentLength == 0) { return; } // 计算上传进度百分比 double percent = (double) pBytesRead / (double) pContentLength; // 将百分比存储在用户会话中 WebContext.getContext().getSession().put("upload_progress", percent); } }
#Configure the interface implementation class into the ymp.configs.webmvc.upload_file_listener_class parameter;
Obtain the progress value in the session through Ajax timed round robin and display it on the page;