Method of Transforming MultipartFile into File in java

  • 2021-12-04 10:13:55
  • OfStack

Directory MultipartFile to FileFile to MultipartFile PS: file to base64 String

MultipartFile to File

The company business needs to receive the picture or file submitted by the front desk (multipart/form-data) type (ps: I don't know if it is misspelled)

Background reception needs to be converted to 1 File type

Then the problem of type conversion is involved here:

Let me list my code first:


@PostMapping("upload")
    @ResponseBody
    public void upload(HttpServletResponse response,MultipartFile file)throws IOException{
        //MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
        PrintWriter writer = response.getWriter();
        File f = null;
        if(file.equals("")||file.getSize()<=0){
            file = null;
        }else{
            InputStream ins = file.getInputStream();
            f=new File(file.getOriginalFilename());
            FileUtil.inputStreamToFile(ins, f);
        }
 
        JSONObject jsonObject= weChatMaterialService.getMediaId("image",f);
        writer.print(jsonObject);
        writer.flush();
        writer.close();
 
        File del = new File(f.toURI());
        del.delete();
        System.out.println(jsonObject);
 
    }

Now let's dissect it: It is to judge whether the file I received is empty, and if it is not empty, it will be converted into the form of stream

After that FileUtil is to transfer to File, the last step is because this approach will be in the root directory of the project (like the root directory, I'm not sure, but also now learn to use hee hee) to generate a file, this is what we don't need, right, and then delete it on the line


File f = null;
        if(file.equals("")||file.getSize()<=0){
            file = null;
        }else{
            InputStream ins = file.getInputStream();
            f=new File(file.getOriginalFilename());
            FileUtil.inputStreamToFile(ins, f);
        }
 
public class FileUtil {
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}
 File del = new File(f.toURI());
        del.delete();

File to MultipartFile

Add dependencies


<!-- https://mvnrepository.com/artifact/org.springframework/spring-mock -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-mock</artifactId>
    <version>2.0.8</version>
</dependency>

Code


/**
  * @param
  * @return
  * @author:liuyu
  * @ Creation date :2020 Year 3 Month 5 Day 
  * @ Function description: File Turn MultipartFile
  */
 private static MultipartFile fileToMultipartFile(File file) throws Exception {
  InputStream inputStream = new FileInputStream(file);
  MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
  return multipartFile;

 }

PS: file to base64 String

① java files are converted into base 64 characters


 FileInputStream inputFile = new FileInputStream(f);
 String base 64=null;
  byte[] buffer = new byte[(int) f.length()];
  inputFile.read(buffer);
  inputFile.close();
  base64=new BASE64Encoder().encode(buffer);

② Note: When using BASE64Enconder (). encode (buffer) in java, there will be a string newline problem, because RFC 822 stipulates that every 72 characters are added with a newline symbol, which will cause problems when using base64 strings, so we should solve the newline problem first when using it


String encoded = base64.replaceAll("[\\s*\t\n\r]", "");

Related articles: