一、SpringMVC实现文件的上传
Spring MVC 上下文中默认没有为文件上传提供了直接的支持,因 此默认情况下不能处理文件的上传工作,
如果想使用 Spring 的文件上传功能,需现在上下文中配置 CommonsMultipartResovler:
二、文件上传的步骤:
1.加入jar包:
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
2.在SpringMVC配置文件中配置CommonsMultipartResovler
<!-- 配置文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <property name="maxUploadSize" value="1024000"></property> </bean>
3.前端表单:注意:需要请求方式:POST,input类型:file,属性:enctype="multipart/form-data"
<form action="${pageContext.request.contextPath }/testUpload" method="post" enctype="multipart/form-data"> file:<input type="file" name="photo"> desc:<input type="text" name="desc"> <input type="submit" value="上传"> </form>
4.文件上传方法的实现
@RequestMapping("/testUpload") public String testUpload(HttpServletRequest request,@RequestParam(value="desc",required=false)String desc,@RequestParam("photo") CommonsMultipartFile file){ ServletContext servletContext = request.getServletContext(); String realPath = servletContext.getRealPath("/upload"); File file1 = new File(realPath); if(!file1.exists()){ file1.mkdir(); } OutputStream out = null; InputStream in = null; //uuid_name.jpg String prefix = UUID.randomUUID().toString(); prefix = prefix.replace("-",""); String fileName = prefix+"_"+file.getOriginalFilename(); System.out.println(fileName); try { out = new FileOutputStream(new File(realPath+"\\"+fileName)); in = file.getInputStream(); //创建一个缓冲区 byte buffer[]=new byte[1024]; //判断输入流中的数据是否已经对完 int len=0; //循环将输入流读入到缓冲区中(len=in.read(buffer)>0)表示in里面还有数据 while((len=in.read(buffer))!=-1){ //使用FileOutPutStream输出流,将缓冲区的数据输出到指定目录文件 out.write(buffer,0,len); } } catch (Exception e) { e.printStackTrace(); } //关闭输入流、输出流 try { out.close(); in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "success"; }
三、文件的下载
文件能上传就能下载
1.用ResponseEntity<byte[]> 返回值完成文件下载:
@RequestMapping(value="/testDownLoad") public ResponseEntity<byte[]> testDonwLoad(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 status=HttpStatus.OK; ResponseEntity<byte []> responseEntity=new ResponseEntity<>(body, headers,status); in.close(); return responseEntity; }
时间: 2024-10-09 21:42:17