本文共 2056 字,大约阅读时间需要 6 分钟。
file upload controller class for handle multipart file upload requestcom.controller.FileUploadControllerclass FileUploadController implements file upload functionality with progress trackinglog = logger.getLogger(FileUploadController.class)upload method implementation@Controller@RequestMapping("/upload.html")public ModelAndView upload(HttpServletRequest request, HttpServletResponse response) throws Exception {create session instancesession = request.getSession()modelAndView = new ModelAndView()check if request is multipartisMultipart = ServletFileUpload.isMultipartContent(request)if (!isMultipart) { return modelAndView;}create disk file item factoryFileItemFactory factory = new DiskFileItemFactory();initialize file upload serviceuploadService = new ServletFileUpload(factory);set progress listeneruploadService.setProgressListener(new ProgressListener() { // progress updating logic public void update(long bytesRead, long contentLength, int items) { ProcessInfo info = new ProcessInfo(); info.itemNum = items; info.readSize = bytesRead; info.totalSize = contentLength; info.show = String.format("%d/%d byte", bytesRead, contentLength); info.rate = (int)(Math.round((float)bytesRead / contentLength * 100)); session.setAttribute("processInfo", info); }});parse requestitems = uploadService.parseRequest(request)process uploaded itemsforeach (item in items) { if (item is form field) { // handle common form fields } else { // handle file upload fields String fileName = item.getName(); String contentType = item.getContentType(); File uploadedFile = new File(("c://" + fileName)); item.write(uploadedFile); }}return modelAndView}process method for getting progress info@RequestMapping("/process.json", method=RequestMethod.GET)@ResponseBodypublic Object process(HttpServletRequest request, HttpServletResponse response) throws Exception { return session.getAttribute("processInfo");}class ProcessInfo { // properties and fields}
转载地址:http://dmeyk.baihongyu.com/