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

下载:

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.     }  
上一篇:jquery操作select(取值,设置选中) 基础


下一篇:发现一php木马代码