springmvc file upload and download

SpringMVC for file upload and download
relative JavaWeb stage we used the servlet for file uploading and downloading operations; and SpringMVC achieve direct support for upload operation, providingmultipartparser. MultipartFileIt provides methods for file operations, making it easier to upload files. Whether uploading or downloading is to convert the binary stream, let's understand the form of a case of how to use the upload SpringMVC implementation file.

File Upload

ready

To understanding

  1. File upload We first thing to consider is where to upload the file? It is uploaded to the project directory, or upload it to your local disk?
  2. Since uploaded files are generally binary files, so we need some way to submit a form to be encoded. By enctypesetting multipart/form-data, for each input field will submit (the default form submitted as a data storage format different portions POST request 名字-值, is clearly not suitable for the kind of file upload similar binary data).
  3. Spring provides a multipartparser data CommonsMultipartResolver( MultipartResolverinterface implementation class), but this parser is based on the Apache Commons FileUploadtechnology, so the need commons-filrUpload.jarto support.

Configuration

In addition Before we used Spring and SpringMVC the first off the jar dependencies, also need to import the following jar files:

<!--文件上传下载-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
在springmvc.xml中配置上传下载解析器
<! - uploading and downloading parser -> 
<bean the above mentioned id = "the MultipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver">
<Property name = "defaultEncoding" value = "UTF-8"> < / Property>
<Property name = "maxUploadSize" value = "10485760"> </ Property> <- set the maximum size supported upload B ->!
</ the bean>
front Code example:

 

 The sample code background

 @RequestMapping("/insertMovie")
    @ResponseBody
    public Map<String,String> insertMovie(@RequestParam(value="file",required = false) MultipartFile file,
                                          Movie movie,
                                          HttpServletRequest request
                                          ){
        Map<String,String> ret = new HashMap<String,String>();
        Movie movie1 = movieServices.selectMovieByName(movie.getMovieCname());
        if (movie1!=null){
         ret.put("type","error");
         ret.put ( "MSG", "movie already exists, do not add the second" );
          return RET; 
        } 
        IF (. movie.getMovieDetail () length ()> 255 ) { 
            ret.put ( "type", "error " ); 
            ret.put ( " msg "," film details the text is too long, please provide a brief description " );
             return RET; 
        } 

      IF (file.getSize ()> 10485760 ) { 
          ret.put ( " of the type "," error " ); 
          ret.put ( "msg", "file size no larger than 10M" );
            return RET;
      }
      String oldName = file.getOriginalFilename();
      Of the type String = oldName.substring (oldName.lastIndexOf () + 1 "." , OldName.length ());
       IF ( "JPG, jpeg, GIF, PNG"! .ToUpperCase () the contains (type.toUpperCase ()). ) { 
          ret.put ( "of the type", "error" ); 
          ret.put ( "msg", "add the suffix images JPG, jpeg, GIF, Pang" );
           return RET; 
      } 
      // upload pictures to saved path, the path for the movie poster movies / movie name / picture / picture 
        String path = request.getSession (). getServletContext (). getRealPath ( "static / static / movies /" + movie.getMovieCname () + "/ picture / " ); 
        File target = new new File (path);
        if (!target.exists()){
            target.mkdirs();
        }

      String newName = System.currentTimeMillis()+"."+type;

        try {
            file.transferTo(new File(target,newName));
        } catch (IOException e) {
            e.printStackTrace();
            ret.put("type","error");
            ret.put("msg","文件保存异常");
            return ret;

        }
        //电影海报的项目绝对路径
        movie.setMoviePicture("static/static/movies/"+movie.getMovieCname()+"/picture/"+newName);
        //When added by default, the state of the film is set to 1, representing aggressively 
        movie.setMovieState (1 );
         int I = movieServices.insertMovie (Movie);
         IF (I <0 ) { 
            ret.put ( "type", "error" ) ; 
            ret.put ( "msg", "add failed" );
             return RET; 
        } 

        ret.put ( "of the type", "success" ); 
        ret.put ( "msg", "added successfully" ); 

        return RET; 

    }
View Code

 

 

 

Guess you like

Origin www.cnblogs.com/ghwq/p/12446660.html