


Java Spring MVC upload and download file configuration and controller method detailed explanation
下载:
1.在spring-mvc中配置(用于100M以下的文件下载)
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!--配置下载返回类型--> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <!--配置编码方式--> <property name="supportedMediaTypes" value="application/json; charset=UTF-8" /> </bean> </list> </property> </bean>
下载文件代码
@RequestMapping("/file/{name.rp}") public ResponseEntity<byte[]> fileDownLoad(@PathVariable("name.rp")String name, HttpServletRequest request,HttpServletResponse response) { // @PathVariable String name, // @RequestParam("name")String name, // System.out.println("<name>"+name); // System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); ResponseEntity<byte[]> re = null; try { /** * css,js,json,gif,png,bmp,jpg,ico,doc,docx,xls,xlsx,txt,swf,pdf * **/ //下载防止静态加载干扰 Feelutile f=new Feelutile(); name=f.getfileformat(name); String pathString="C:\\tempDirectory\\"+name; File file=new File(pathString); HttpHeaders headers=new HttpHeaders(); //String filename=URLEncoder.encode(name, "UTF-8");//为了解决中文名称乱码问题 String filename=new String(name.getBytes("utf-8"),"utf-8"); byte[] by=FileUtils.readFileToByteArray(file); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //URLEncoder.encode(filename, "UTF-8") headers.setContentDispositionFormData("attachment",filename); headers.setContentLength(by.length); re=new ResponseEntity<byte[]>(by, headers, HttpStatus.CREATED); } catch (Exception e) { e.printStackTrace(); try { request.getRequestDispatcher("/error/404.jsp").forward(request, response); } catch (ServletException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return re; }
上传文件:
1在spring-mvc中配置
<!--4.文件上传 配置 file upload --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>1048576000</value> </property> <property name="maxInMemorySize"> <value>40960</value> </property> </bean>
在controller中代码如下
@RequestMapping(value="/upload", method = RequestMethod.POST) @ResponseBody public Json upload(Doc doc, @RequestParam("uploadFile") CommonsMultipartFile file) { Json j = new Json(); try { String realpath = this.servletContext.getRealPath("/upload"); String uploadFileFileName = file.getOriginalFilename(); String uploadFileFileNameWithoutSpace = uploadFileFileName.replaceAll(" ", ""); String fileType = uploadFileFileNameWithoutSpace.substring(uploadFileFileNameWithoutSpace.lastIndexOf(".")); File targetFile = new File(realpath+File.separator, uploadFileFileNameWithoutSpace); if (targetFile.exists()) { targetFile.delete(); } file.getFileItem().write(targetFile); docService.upload(doc,uploadFileFileNameWithoutSpace); j.setSuccess(true); j.setMsg("Upload manual successfully"); }catch (Exception e) { logger.error(ExceptionUtil.getExceptionMessage(e)); j.setMsg("Upload manual unsuccessfully"); } return j; }
以上所述是小编给大家介绍的Java Spring MVC 上传下载文件配置及controller方法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!
更多Java Spring MVC 上传下载文件配置及controller方法详解相关文章请关注PHP中文网!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Start Spring using IntelliJIDEAUltimate version...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...
