MultipartFile and File

Absrtact: in a certain period of time, we encountered the need to transfer files. We need to use HttpClient to transfer files. In the process of realizing this requirement, we use MultipartFile and File.

This article is shared from Huawei cloud community< MultipartFile and File >, author: Copy engineer.

preface

In a certain period of time, when you encounter the need to transfer files, you need to use HttpClient to transfer the following files. The process is as follows:

MultipartFile and File are used in the process of implementing this requirement, and I am not very familiar with the previous one. Record it

What is MultipartFile

MultipartFile is of spring type and represents the file uploaded in form data mode in HTML, including binary data + file name. [know from Baidu]

Conversion between MultipartFile and File

1. File to MultipartFile

(1) : use org springframework. mock. web. Mockmultipartfile needs to import spring test jar

public static void main(String[] args) throws Exception {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        // MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream)
        // Where originalFilename,String contentType, old name, type can be empty
        // ContentType.APPLICATION_OCTET_STREAM.toString() requires a package using HttpClient
        MultipartFile multipartFile = new MockMultipartFile("copy"+file.getName(),file.getName(),ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
        System.out.println(multipartFile.getName()); // Output CopyTest txt
    }

(2) : using CommonsMultipartFile

public static void main(String[] args) throws Exception {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        // You need to import the Commons fileUpload package
        FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
           while ( (n = inputStream.read(buffer,0,4096)) != -1){
               os.write(buffer,0,n);
           }
            //You can also use ioutils copy(inputStream,os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(multipartFile.getName());
        }catch (IOException e){
            e.printStackTrace();
        }

    }

2. MultipartFile to File

(1) : the reverse process of using File to MultipartFile

When you look at this code, you will feel familiar with it. Yes, this is the reverse process of converting File to MultipartFile. This method will generate a File in the root directory, and you need to delete the File.

 public static void main(String[] args) throws Exception {
        int n;
        // Get MultipartFile file
        MultipartFile multipartFile = getFile();
        File f = null;
        // The new name of the output file refers to the name of the uploaded file
        System.out.println("getName:"+multipartFile.getName());
        // The output source file name refers to the file name before uploading
        System.out.println("Oriname:"+multipartFile.getOriginalFilename());
        // create a file
        f = new File(multipartFile.getOriginalFilename());
        try ( InputStream in  = multipartFile.getInputStream(); OutputStream os = new FileOutputStream(f)){
            // Get the file stream. Output to a new file as a file stream
            // You can use byte [] SS = multipartfile getBytes(); Replace while
            byte[] buffer = new byte[4096];
            while ((n = in.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            // Read the first line of the file
            BufferedReader bufferedReader = new BufferedReader(new FileReader(f));
            System.out.println(bufferedReader.readLine());
            // Output path
            bufferedReader.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        // URL of the output file
        System.out.println(f.toURI().toURL().toString());
        // Absolute path to the output file
        System.out.println(f.getAbsolutePath());
        // After the operation, you need to delete the files generated in the root directory
        File file = new File(f.toURI());
        if (file.delete()){
            System.out.println("Delete succeeded");
        }else {
            System.out.println("Deletion failed");

        }

    }
    /**
     *
     * @Description Return MultipartFile file
     * @return org.springframework.web.multipart.MultipartFile
     * @date 2019/1/5 11:08
     * @auther dell
     */
    public static MultipartFile getFile() throws IOException {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
            while ( (n = inputStream.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            //You can also use ioutils copy(inputStream,os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(multipartFile.getName());
            return multipartFile;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

(2) : transferTo is used (in essence, the flow is used, but the steps are encapsulated)

Files will be generated, and finally no files need to be deleted

public static void main(String[] args) throws Exception {
        String path = "F:\\demo\\";
        File file = new File(path,"demo.txt");
        // Get MultipartFile file
        MultipartFile multipartFile = getFile();
        /*byte[] ss = multipartFile.getBytes();
        OutputStream os = new FileOutputStream(file);
        os.write(ss);
        os.close();*/
        multipartFile.transferTo(file);
        // Read the first line of the file
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        System.out.println(bufferedReader.readLine());
        // Output absolute path
        System.out.println(file.getAbsolutePath());
        bufferedReader.close();
        // After the operation, you need to delete the files generated in the root directory
        if (file.delete()){
            System.out.println("Delete succeeded");
        }else {
            System.out.println("Deletion failed");

        }
    }
    /**
     *
     * @Description Return MultipartFile file
     * @return org.springframework.web.multipart.MultipartFile
     * @date 2019/1/5 11:08
     * @auther dell
     */
    public static MultipartFile getFile() throws IOException {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
            while ( (n = inputStream.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            //You can also use ioutils copy(inputStream,os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(multipartFile.getName());
            return multipartFile;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

(3) : use FileUtils copyInputStreamToFile()

It will also generate files, and finally delete files

public static void main(String[] args) throws Exception {
        String path = "F:\\demo\\";
        File file = new File(path,"demo.txt");
        // Get MultipartFile file
        MultipartFile multipartFile = getFile();
        // Output stream to file
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),file);
        // Read the first line of the file
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        System.out.println(bufferedReader.readLine());
        // Output absolute path
        System.out.println(file.getAbsolutePath());
        bufferedReader.close();
        // After the operation, you need to delete the files generated in the root directory
        if (file.delete()){
            System.out.println("Delete succeeded");
        }else {
            System.out.println("Deletion failed");

        }
    }
    /**
     *
     * @Description Return MultipartFile file
     * @return org.springframework.web.multipart.MultipartFile
     * @date 2019/1/5 11:08
     * @auther dell
     */
    public static MultipartFile getFile() throws IOException {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
            while ( (n = inputStream.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            //You can also use ioutils copy(inputStream,os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(multipartFile.getName());
            return multipartFile;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

4: Forced rotation type

CommonsMultipartFile commonsmultipartfile = (CommonsMultipartFile) multipartFile;
DiskFileItem diskFileItem = (DiskFileItem) commonsmultipartfile.getFileItem();
File file = diskFileItem.getStoreLocation();

The file you get is just an empty shell

The only thing you can get is f: \ upload_ edfce39f_ 2894_ 4b66_ b865_ d5fb8636bdf3_ It is said on the tmp that temporary files will be generated in the root directory. It can also be seen from the tmp that it is a temporary file, but I have tried several times and found nothing.... It is inevitable that the file cannot be found by directly obtaining the read content of this file. Of course, it is troublesome to configure CommonsMultipartResolver in the spring configuration file....

However, we can take a look at diskFileItem to see if the following figure is very familiar. You can get the file stream from diskFileItem. In fact, you know that you get the file stream from here when you look at the source code. The rest is easy to do, so I won't repeat it /.

When using temporary files, you can use buffers to create temporary files

//  createTempFile(String prefix, String suffix) 
//  prefix file name suffix file format
// The default is TMP format C: \ users \ Dell \ appdata \ local \ temp \ tmp8784723057512789016 tmp 
File file =File.createTempFile("tmp", null);
// Txt format C: \ users \ Dell \ appdata \ local \ temp \ tmp2888293586594052933 txt
File file =File.createTempFile("tmp", ".txt");

HttpClient builds upload file parameters and realizes transfer files

I don't give examples here. I refer to the codes of other blogs

// Get file name
String fileName = file.getOriginalFilename();
HttpPost httpPost = new HttpPost(url);
// Create file upload entity
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
builder.addTextBody("filename", fileName);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// Execute commit

After submitting, you will find that the file name you uploaded will appear Chinese garbled code

The solution I use is:

 //Set the mode to RFC6532
 builder.setMode(HttpMultipartMode.RFC6532);

Click follow to learn about Huawei's new cloud technology for the first time~

Keywords: Java Spring File

Added by ernielou on Sat, 22 Jan 2022 02:26:40 +0200