Java-spring-mvc _ configure the controller file in the upper and lower layers, java-spring-mvc

Source: Internet
Author: User

Java-spring-mvc _ configure the controller file in the upper and lower layers, java-spring-mvc

Download:

1. Configure in spring-mvc (for downloading files below MB)
  1. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
  2. <property name="messageConverters"> 
  3. <list> 
  4. <! -- Configure the download return type -->
  5. <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> 
  6.  
  7. <bean class="org.springframework.http.converter.StringHttpMessageConverter"> 
  8. <! -- Configure the encoding method -->
  9. <property name="supportedMediaTypes" value="application/json; charset=UTF-8" /> 
  10. </bean> 
  11. </list> 
  12. </property> 
  13. </bean>
Download file code
  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
    ***/
    // Download to Prevent Static Loading interference
    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"); // to solve Chinese name garbled Problem
    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;
    }

Upload File: 1 configure in spring-mvc
  1. <! -- 4. file upload Configuration 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>
 

The code in controller is as follows:


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.