Upload and download files / pictures with springboot

Time:2021-3-4
  • Import dependency( pom.xml )

commons-io
            commons-io
            2.6
        
        
            commons-fileupload
            commons-fileupload
            1.3.3
        
        
        
            javax.servlet
            javax.servlet-api
            4.0.1
        
        
        
            net.coobird
            thumbnailator
            0.4.8
  • Global configuration application.properties

#Upload file size
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
  • Create webmvcconfigConfiguration classStatic resource mapping

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String dirPath = jarF.getParentFile().toString()+"/upload/";

        String os = System.getProperty("os.name");

        if ( os.toLowerCase (). Startswith ("win") {// if it is a Windows system
            registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
        } else {
            registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
        }
    }

}
  • Control layer
//Upload file
    @ResponseBody
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("files") MultipartFile files) throws IOException {
//// win system upload path save settings
//// get project path
//        File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
//// absolute path = project path + custom path
//        File pathFile = new File(projectPath.getAbsolutePath(), "static/upload/");
//        if (!pathFile.exists()) {
//            pathFile.mkdirs();
//        }
//// upload file address
//        UUID uuid = UUID.randomUUID();
//        File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
//        files.transferTo(serverFile);
//
//        String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\", "/");
//
//        return imgPath;

        //Linux server upload path save settings
        //Project path / home / www/
        File pathFile = new File("/home/www/upload/");
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        //Upload file address
        UUID uuid = UUID.randomUUID();
        File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
        files.transferTo(serverFile);

        String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\", "/");

        return imgPath;
    }
  • HTML page upload without Ajax refresh

Picture upload
    
    Upload pictures
  • JS

//General picture upload
        $('#img_upload').click(function () {
            var formData = new FormData();
            //Get selected files
            $.each($('input[name="files"]'),function (index,item) {
                formData.append("files",item.files[0])
            });

            //Send asynchronous request
            $.ajax({
                method:'post',
                URL: '[@ {/ user / upload}]]', // file upload interface
                data:formData,
                processData: false,
                contentType:false,
                success:function (data) {
                    //The trigger method is returned successfully
                    $('#imgPath').val(data);
                    Alert ("upload successful");
                },
                //Method of triggering request failure
                error:function () {
                    Alert ("upload failed");
                }
            });
        });
  • File or picture download

  • Control layer
@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
   //Picture address to download
   String  path = request.getServletContext().getRealPath("/upload");
   String filename = basic syntax. JPG;

   //1. Set response header
   response.reset (); // set the page not to cache, clear the buffer
   response.setCharacterEncoding ("UTF-8"); // character encoding
   response.setContentType ("multipart / form data"); // binary transmission data
   //Set response header
   response.setHeader("Content-Disposition",
           "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

   File file = new File(path,fileName);
   //2. Read file -- input stream
   InputStream input=new FileInputStream(file);
   //3. Write out file -- output stream
   OutputStream out = response.getOutputStream();

   byte[] buff =new byte[1024];
   int index=0;
   //4. Perform write operation
   while((index= input.read(buff))!= -1){
       out.write(buff, 0, index);
       out.flush();
  }
   out.close();
   input.close();
   return null;
}
  • HTML page

Click download

 

 

reference material:Luna says spring MVC: file upload and download

Website:https://www.cnblogs.com/dmflysky/p/14450015.html

Recommended Today

Rust and python: why rust can replace Python

In this guide, we compare the rust and python programming languages. We will discuss the applicable use cases in each case, review the advantages and disadvantages of using rust and python, and explain why rust might replace python. I will introduce the following: What is rust? What is Python? When to use rust When to […]