SpringMVC实现文件的上传和下载 淡淡的烟草味﹌ 2022-06-09 02:11 212阅读 0赞 一、文件的上传 大体可分为以下几步: 1.导入架包; 2.配置springmvc.xml文件; 3.写上传文件的页面; 4.写Controller层下的请求所对应的映射。 Spring MVC 上下文中默认没有为文件上传提供了直接的支持,因此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需现在上下文中配置 CommonsMultipartResovler 1.导入以下两个架包; commons-fileupload-1.3.1.jar commons-io-2.4.jar 2.配置springmvc.xml文件 <!-- 配置CommonsMultipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property><!-- 默认编码 --> <property name="maxUploadSize" value="102400"></property><!-- 以字节为单位,设置最大上传文件的大小限制 --> </bean> 3.写上传文件的页面 <form action="${pageContext.request.contextPath }/testUpload" method="post" enctype="multipart/form-data"> file:<input type="file" name="photo"><br> desc:<input type="text" name="desc"> <input type="submit" value="提交"> </form> 注意:表单:POST请求,file类型,enctype="multipart/form-data" 4. 写Controller层下的请求所对应的映射。 @RequestMapping(value="/testUpload",method=RequestMethod.POST) public String testUpload(HttpServletRequest request,@RequestParam(value="desc") String desc,@RequestParam(value="photo") CommonsMultipartFile file) throws IOException{ ServletContext servletContext = request.getServletContext(); //得到真实路径 String realPath = servletContext.getRealPath("/upload"); File file1 = new File(realPath); if(!file1.exists()){ //判断该文件是否存在,不存在将新建一个 file1.mkdir(); } OutputStream out; InputStream in; //uuid_name.jpg String prefix = UUID.randomUUID().toString(); prefix = prefix.replace("-","");//将UUID中的-去掉 String fileName = prefix+"_"+file.getOriginalFilename(); //防止一个文件多次上传造成的重名的问题;getOriginalFilename获取上传文件的名字 System.out.println(fileName); out = new FileOutputStream(new File(realPath+"\\"+fileName)); in = file.getInputStream(); /*byte[] bt=new byte[1024]; 原生态处理方法 int a=0; while((a=in.read(bt))!=-1){ out.write(bt,0,a); }*/ IOUtils.copy(in, out); out.close(); in.close(); return "success"; } 二、文件的下载 用ResponseEntity<byte\[\]> 返回值完成文件下载: @RequestMapping(value="/testdownload") public ResponseEntity<byte[]> testdownload(HttpServletRequest request) throws Exception{ ServletContext servletContext = request.getServletContext(); String fileName = "风吹麦浪.mp3"; //获得源文件的路径,即在服务器上的路径 String realPath = servletContext.getRealPath("/WEB-INF/"+fileName); InputStream in =new FileInputStream(new File(realPath)); byte[] body = new byte[in.available()]; in.read(body); MultiValueMap<String, String> headers=new HttpHeaders(); fileName= new String(fileName.getBytes("gbk"), "iso8859-1"); headers.set("Content-Disposition","attachment;filename="+fileName); HttpStatus statusCode=HttpStatus.OK;//状态 ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode); in.close(); return response; } }
还没有评论,来说两句吧...