Springboot file upload and download

created at 03-25-2022 views: 7

foreword

The project I am working on requires automatic updates, so first of all, we need to upload files to a certain path on the server and download them from the server, so make a record here.

1 Upload files

controller

@Autowired
     private FileService fileService;
     @Value("${path.app}")
     private String OTHER_UPLOAD_PATH;
     @Value("${path.picture}")
     private String PICTURE_UPLOAD_PATH ;

     //Upload interface, isPicture simply classifies whether it is a picture or not, and then can be changed to pass in a string corresponding to a different path
     @PostMapping(value = "/uploadFile",consumes= MediaType.MULTIPART_FORM_DATA_VALUE)
     public R upload(@RequestParam("file") MultipartFile file, Boolean isPicture) throws Exception {
         if(isPicture){
             return fileService.upload(file,PICTURE_UPLOAD_PATH,isPicture);
         }
         return fileService.upload(file,OTHER_UPLOAD_PATH,isPicture);
     }

service

@Autowired
    SnowflakeUtil snowflakeUtil;

    @Value("${server.port}")
    private String port;
    @Value("${server.ip}")
    private String ip;
    //implementation of upload interface
    @Override
    public R upload(MultipartFile file, String uploadFilePath, Boolean isPicture) throws Exception {
    //return if the file is empty
        if (file.isEmpty())
            return null;
        UploadInfo uploadInfo = new UploadInfo();
        String originalFilename;
        String originalFilenameWithoutSuffix="";
        String fileName;
        String suffix;
        //Get the uploaded file name (with suffix)
        originalFilename = file.getOriginalFilename();
        //Get the uploaded file name (without suffix)
        for(int i=0;i<originalFilename.split("\\.").length-1;i++) {
            originalFilenameWithoutSuffix += originalFilename.split("\\.")[i] + ".";
        }
        //get file suffix
        suffix = originalFilename.split("\\.")[originalFilename.split("\\.").length-1];
        //The name of the file uploaded to the server
        fileName = originalFilenameWithoutSuffix + UUID.randomUUID().toString() + '.' + suffix;
        //get file type
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        //get file size
        long fileSize = file.getSize();
        File packageFile = new File(uploadFilePath);
        if (!packageFile.exists()) {
            packageFile.mkdir();
        }
        File targetFile = new File(uploadFilePath + "/" + fileName);
        file.transferTo(targetFile);
        // set return information
        uploadInfo.setId(snowflakeUtil.getSnowflakeId());
        uploadInfo.setBeginFileName(originalFilename);
        uploadInfo.setLastFileName(fileName);
        uploadInfo.setFileType(fileType);
        uploadInfo.setFileSize(Long.toString(fileSize));
        uploadInfo.setUploadUrl(targetFile.toString());
        //Construct access link
        if(isPicture)
        {
            uploadInfo.setVisitUrl("http://" + ip + ":" + port + "/file/images/" + uploadInfo.getLastFileName());
        }else{
            uploadInfo.setVisitUrl("http://"+ip+":"+port+"/file/"+uploadInfo.getLastFileName());
        }
        //Construct download link
        uploadInfo.setDownloadUrl("http://" + ip + ":" + port + "/file/download?fileName=" + uploadInfo.getLastFileName() + "&isPicture=" + isPicture);
        uploadInfo.setResult("Upload successful");
        // save the download record into the database
        baseMapper.record(uploadInfo);
        return R.ok().message("success").data("info",uploadInfo);
    }

2 Download

controller

//Download interface, used when constructing the download link
     @RequestMapping("/download")
     @ResponseBody
     public void download(HttpServletResponse response,String fileName,Boolean isPicture) throws UnsupportedEncodingException {
         if(isPicture){
             fileService.download(response, PICTURE_UPLOAD_PATH, fileName,isPicture);
         }else{
             fileService.download(response, OTHER_UPLOAD_PATH, fileName,isPicture);
         }
     }

service

@Override
    public void download(HttpServletResponse response, String path, String fileName, Boolean isPicture) throws UnsupportedEncodingException {
    // location of the file
        String FullPath = path + fileName;
        File packetFile = new File(FullPath);
        //downloaded file name
        String fn = packetFile.getName();
        System.out.println("filename:"+fn);
        File file = new File(FullPath);
        // If the filename exists, download it
        if (file.exists()) {
            // download configuration file
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // The downloaded file can display Chinese normally
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // implement file download
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println(response.getWriter());
                System.out.println("Successful download");
            } catch (Exception e) {
                System.out.println("mistake:"+e.getMessage());
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            //The corresponding file does not exist
            System.out.println("File does not exist");
            return;
        }
    }

Note that the download link can only be tested in the browser, so that it will be downloaded directly. If you use postman directly, you will see the garbled code returned.

created at:03-25-2022
edited at: 05-31-2022: