java-spring-mvc_上傳下載檔案配置及controller方法,java-spring-mvc

來源:互聯網
上載者:User

java-spring-mvc_上傳下載檔案配置及controller方法,java-spring-mvc

下載:

1.在spring-mvc中配置(用於100M以下的檔案下載)
  1. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
  2. <property name="messageConverters"> 
  3. <list> 
  4. <!--配置下載傳回型別-->
  5. <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> 
  6.  
  7. <bean class="org.springframework.http.converter.StringHttpMessageConverter"> 
  8. <!--配置編碼方式-->
  9. <property name="supportedMediaTypes" value="application/json; charset=UTF-8" /> 
  10. </bean> 
  11. </list> 
  12. </property> 
  13. </bean>
下載檔案代碼
  1. @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中配置
  1. <!--4.檔案上傳 配置 file upload -->
  2.     <bean id="multipartResolver"
  3.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  4.         <property name="defaultEncoding">
  5.             <value>UTF-8</value>
  6.         </property>
  7.         <property name="maxUploadSize">
  8.             <value>1048576000</value>
  9.         </property>
  10.         <property name="maxInMemorySize">
  11.             <value>40960</value>
  12.         </property>
  13.     </bean>
 

在controller中代碼如下


  1. @RequestMapping(value="/upload", method = RequestMethod.POST)
  2.     @ResponseBody
  3.     public Json upload(Doc doc, @RequestParam("uploadFile") CommonsMultipartFile file) {
  4.         Json j = new Json();
  5.         
  6.         try {
  7.             String realpath = this.servletContext.getRealPath("/upload");            
  8.             String uploadFileFileName = file.getOriginalFilename();            
  9.             String uploadFileFileNameWithoutSpace = uploadFileFileName.replaceAll(" ", "");        
  10.             String fileType = uploadFileFileNameWithoutSpace.substring(uploadFileFileNameWithoutSpace.lastIndexOf("."));
  11.             
  12.             File targetFile = new File(realpath+File.separator, uploadFileFileNameWithoutSpace);
  13.             if (targetFile.exists()) {
  14.                 targetFile.delete();
  15.             }
  16.             file.getFileItem().write(targetFile);        
  17.             docService.upload(doc,uploadFileFileNameWithoutSpace);
  18.             
  19.             j.setSuccess(true);
  20.             j.setMsg("Upload manual successfully");
  21.             
  22.         }catch (Exception e) {
  23.             logger.error(ExceptionUtil.getExceptionMessage(e));
  24.             j.setMsg("Upload manual unsuccessfully");
  25.         }
  26.         
  27.         return j;
  28.     }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.