springmvc upload and download
The jar package must be imported
If it is a maven project import dependencies
<!-- file upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency>
The CommonsMultipartResolver file parser is defined under the spring's servlet view parser, which is to run the project when this is added. If there is no fileuload-related jar package, an error will be reported.
Write xml configuration in spring mvc configuration file
<!-- Definition file interpreter --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- set default encoding--> <property name="defaultEncoding" value="utf-8"></property> <!-- The maximum upload image size is 5M--> <property name="maxUploadSize" value="5242440"></property> </bean>
code demo
@RequestMapping("file") @Controller public class FileController { /** * File upload function * @param file * @return * @throws IOException */ @RequestMapping(value="/upload",method=RequestMethod.POST) @ResponseBody public String upload(MultipartFile file,HttpServletRequest request) throws IOException{ String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); File dir = new File(path,fileName); if(!dir.exists()){ dir.mkdirs(); } //MultipartFile's own parsing method file.transferTo(dir); return "ok!"; } /** * File download function * @param request * @param response * @throws Exception */ @RequestMapping("/down") public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{ //Simulation file, myfile.txt is the file that needs to be downloaded String fileName = request.getSession().getServletContext().getRealPath("upload")+"/myfile.txt"; //get the input stream InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName))); //If it is downloaded in Chinese name String filename = "download file.txt"; //Transcoding, so as to avoid Chinese garbled file name filename = URLEncoder.encode(filename,"UTF-8"); //Set the file download header response.addHeader("Content-Disposition", "attachment;filename=" + filename); //1. Set the file ContentType type, so setting, will automatically determine the download file type response.setContentType("multipart/form-data"); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); int len = 0; while((len = bis.read()) != -1){ out.write(len); out.flush(); } out.close(); } }