MultipartFile转File 怎么实现

CSDN问答 2021-12-30 13:49:08 阅读数:205

编程开发 实现 file multipartfile CSDN问答

@Slf4j
public class ImageConfig {
public static File multipartFileToFile(MultipartFile file) throws Exception {

 File toFile = null; if (Objects.nonNull(file) && !file.isEmpty()){ String originalFilename = file.getOriginalFilename(); if (StringUtils.isEmpty(originalFilename)) { originalFilename = ""; } toFile = new File(originalFilename); try (InputStream ins = file.getInputStream(); OutputStream os = new FileOutputStream(toFile);){ int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } }catch (Exception e){ log.error(" ",e); throw new InternalException("multipartFileToFile error"); } } return toFile;}

}




采纳答案:

originalFilename 为空,直接返回。

public class ImageConfig {public static File multipartFileToFile(MultipartFile file) throws Exception { File toFile = null; if (Objects.nonNull(file) && !file.isEmpty()){ String originalFilename = file.getOriginalFilename(); if (StringUtils.isEmpty(originalFilename)) { originalFilename = ""; return toFile; } toFile = new File(originalFilename); try (InputStream ins = file.getInputStream(); OutputStream os = new FileOutputStream(toFile);){ int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } }catch (Exception e){ log.error(" ",e); throw new InternalException("multipartFileToFile error"); } } return toFile;}}


其他答案2:

@Slf4j
public class ImageConfig {
public static File multipartFileToFile(MultipartFile file) throws Exception {

 File toFile = null; if (Objects.nonNull(file) && !file.isEmpty()){ String originalFilename = file.getOriginalFilename(); if (StringUtils.isEmpty(originalFilename)) { originalFilename = ""; } toFile = new File(originalFilename); try (InputStream ins = file.getInputStream(); OutputStream os = new FileOutputStream(toFile);){ int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } }catch (Exception e){ log.error(" ",e); throw new InternalException("multipartFileToFile error"); } } return toFile;}

}

版权声明:本文为[CSDN问答]所创,转载请带上原文链接,感谢。 https://ask.csdn.net/questions/7613038