程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> java-spring-mvc_上傳下載文件配置及controller方法,java-spring-mvc

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

編輯:JAVA綜合教程

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.     }  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved