Springboot 2.0 Maven uploads files to remote servers

Posted by phanh on Tue, 30 Jul 2019 23:07:16 +0200

Undertake previous blog posts ” springboot maven+layui upload file“ The file is uploaded to the remote server and returned to the file server storage path and file size needed to store the database.

pom.xml dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.8.1</version>
</dependency>

Here, the method of requesting remote server to upload files is regarded as a tool class, which reduces the repetition of code, reduces the consumption of memory resources and increases the expansibility of code.

  • uploadUrl Server Upload Interface Address
  • LinkedMultiValueMap A key corresponds to multiple values (adding a Key corresponds to multiple Values: void add(K, List))
    public String serverUpload(String tempFilePath) {
        JSONObject jsonObject = null;
        // Setting the request header
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        // Set up the body of the request. Note that LinkedMultiValueMap
        FileSystemResource resource = new FileSystemResource(tempFilePath);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("files", resource);
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        // Cross-domain request server, return jsonObject
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(uploadUrl, files, JSONObject.class);
        jsonObject = responseEntity.getBody();
        // Get the url of the file on the server
        List<String> List = new ArrayList<>();// File Link List
        String data = "";
        if ((Integer) jsonObject.get("statusCode") == 200) {
    //      List = (List<String>) jsonObject.get("data");
    //      src = List.get(0);
            data = jsonObject.get("data").toString();
        }
        return data.substring(1, data.length() - 1);
    //  return src;
    }

File Formatting Tool to Get File Size

    public String formateFileSize(int size) {
        double s = size + 0.0;
        String fileSize = null;
        if (size >= 1048576) {
            fileSize = formateDouble(s / 1048576.0) + "M";
        } else if (size < 1024) {
            fileSize = formateDouble(s) + "B";
        } else {
            fileSize = formateDouble(s / 1024.0) + "K";
        }
        return fileSize;
    }

    public String formateDouble(double value){
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(value);
    }

Simply write a controller to test uploading a picture and returning the remote routing of the picture.

  • System.getProperty("java.io.tmpdir") gets the system temporary directory, Java input and output temporary path
  • file.transferTo(tempFile) writes files to temporary paths and can be uploaded by writing and calling server interfaces.
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String uploadGroupFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        //Determine whether normal members are allowed to upload files
        int size = (int) file.getSize();
        //50MB
        if (size > 52428800L) {
            return jsonResult.error(201, "Oversize Upload Files,Maximum 50 MB");
        }
        // Get the filename
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return "File name cannot be empty";
        }
        // Create temporary files
        String tempFilePath = System.getProperty("java.io.tmpdir") + originalFilename;
        File tempFile = new File(tempFilePath);
        try {
            file.transferTo(tempFile);//Upload files
        } catch (IOException e) {
            e.printStackTrace();
            return "File upload failed!!!";
        }
        //Call the file upload interface if there is no error
        String url = fileUtil.serverUpload(tempFilePath);
        if (tempFile.exists()) {
            tempFile.delete();// Delete temporary files
        }    
        // Format file size
        String fileSize = myFileUtil.formateFileSize(size);
        
        // Database operations...
        
        return url;
    }

Running the project, simply test the interface with postman, and the results are as follows:

Topics: Java Database Apache SpringBoot