After Springboot uploads the file

upload files

For uploading files, most of the things we generally do are save data, manipulate data, transfer data, or manipulate data and then transfer data, or manipulate data and save data, etc. . .

file data processing

There should be several for me now:

  • Save data ( save to local )
  • Consume this file data directly ( without saving it )
  • Send the file data by calling another URL ( transfer data )

Consuming data will be relatively simple, turn it into the form of a file stream, and then eat it with confidence.

1. Consume uploaded data

For direct consumption, this code is sufficient:

This example mainly puts the content of the uploaded file (string stored by line) into an array. The example is simpler, but it is mainly to demonstrate the consumption of uploaded file data, don't mind it.

@PostMapping("/handle-upload-file")
public DataReturnDTO handleUploadFile(@RequestParam MultipartFile multipartFile) {
    // 这个是我自定义的一个返回对象封装,先不管这个
    DataReturnDTO result; 
    ArrayList<String> words = new ArrayList<String>();
    String oneWord;

    // 我们在这里进行上传文件的处理
    try {
        InputStreamReader isr = new InputStreamReader(multipartFile.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        /* 然后在这里进行 br 的处理 */
        while ((oneWord = br.readLine()) != null) {
            words.add(oneWord); 
        }
    } catch (IOException e) { 
    // 一般来说会出现 FileNotFoundException,但是try里面的做法就是为了避免这样的。
        e.printStackTrace();
    }
    return result;
}

However, when you want to save the data or transfer the data, the problem comes. FileNotFoundException often occurs accidentally , which is really a headache. For me who don't know the Springboot mechanism, there is no way to start. . .

2. Upload files to transfer directly

For both uploaded files that are Spring

For the case where the uploaded file needs to be called directly to other URLs (also the uploaded URLs), it will be an error to upload the obtained multipartFile directly. However, most of the Internet says that it needs to be temporarily stored and then sent out as a file stream. It will be successful, but the exception of FileNotFoundException will often occur. I accidentally found the solution on stackoverflow and share it:

Or use the above example as a template

@PostMapping("/handle-upload-file")
public DataReturnDTO handleUploadFile(@RequestParam MultipartFile multipartFile) {
    // 这个是我自定义的一个返回对象封装,先不管这个
    DataReturnDTO result; 
    ArrayList<String> words = new ArrayList<String>();
    String oneWord;

    // 我们在这里进行上传文件的转移
    try {
       byte[] bytes = multipartFile.getBytes();
       String fileName = multipartFile.getOriginalFilename();
       ByteArrayResource resource = new ByteArrayResource(bytes){
           @Override
           public String getFilename(){return fileName;}
       };
       
      // 然后,这个 resource 就可以作为一个上传文件的Object来用了。
       HashMap<String, Object> hashMap = new HashMap<>();
       hashMap.put("file", resource);
       RestTemplate restTemplate = new RestTemplate();

       /* 这里的 url 需要指定的是另外一个上传文件的地址 */
       String result = restTemplate.postForEntity(url, hashMap, String.class);
    
    } catch (IOException e) { 
    // 一般来说会出现 FileNotFoundException,但是try里面的做法就是为了避免这样的。
        e.printStackTrace();
    }
    return result;
}

OK, here, there is one more. That is to save the uploaded file.

3. Save the uploaded file

Here, you need an instance of File, otherwise how to save it? Am I right.

/* java 代码,抱歉这个我还没有测试完,先不写了 */

Summarize

From the above description, there is one thing that has not yet been explained, that is, after Spring uploads files, it will be saved in a temporary path. I personally feel that the data in this path is extremely unstable, which will cause your cached data to be lost if you are not careful. No, or can't find it. According to such a situation, the previous methods 1 and 2 also effectively avoid the exception that the file cannot be found.

However, the specifics of the problem are still not completely clear, so for now, the above approach is a temporary solution. Don't take it to heart, it can be used, I am using it.

It's not too late, let's rest first. I'll update the content here later

link reference

1.Spring MVC save uploaded MultipartFile to specific folder

2. Solve the problem of uploading file path errors using Spring Boot and Multipartfile

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325482767&siteId=291194637