返回博主主页

文件操作

1、前端上传文件 -> 接口接收文件 MultiPartFile -> 转发到其它接口

//a)Multipart 转 File
public static File convert(MultipartFile multipartFile) throws IOException {
	File file = new File(multipartFile.getOriginalFilename());
	FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
	return file;
}
//b)Multipart 转 File
// 或者 MultipartFile 临时存储本地
    private List<File> fileList saveFile(List<MultipartFile> multipartFileList, String dirName) {
	    List<File> fileList = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFileList) {
            String destFile = String.format(Locale.ROOT,
                "%s/%s",
                dirName, multipartFile.getOriginalFilename());
            File file = new File(destFile);
            File dir = file.getParentFile();
            if (!dir.exists()) {
                dir.mkdir();
            }
            try {
                multipartFile.transferTo(file);
				fileList.add(file)
            } catch (Exception ex) {
                log.error("文件转换失败", ex);
                throw new BusinessException("文件转换失败");
            }
        }
		return fileList;
    }
public void embeddingFile(File file, String fileName) {
	JSONObject jsonObject = new JSONObject();
	try {
		HttpResponse response = HttpUtil.createPost("https://xxx")
				.form("file", file, fileName)
				.form("param1", "param1")
				.execute();
		int status = response.getStatus();
		jsonObject = JSONObject.parseObject(response.body(), JSONObject.class);
		if(jsonObject.getInteger("code")!=200){
			throw new Exception("");
		}

	} catch (Exception e) {
		throw new Exception("");
	}

}

  1. 本地模拟前端上传的文件。File->MultipartFile
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-test</artifactId>
</dependency>
 public static MultipartFile getMockMultipartFile(String fileName, String filePath) throws IOException {
        File file = new File(filePath);
        byte[] fileContent = Files.readAllBytes(file.toPath());
        return new MockMultipartFile(fileName, file.getName(), "application/vnd.ms-word", fileContent);
    }

其它 : 将 InputStream 转换为临时 File

使用后可手动删除 file.delete()

    private static File convertInputStreamToFile(InputStream inputStream) throws IOException {
        File tempFile = File.createTempFile("diagnostics", ".tmp");
        tempFile.deleteOnExit(); // jvm 退出自动删除
        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            int read;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
        }
        return tempFile;
    }
posted @ 2024-02-22 09:39  懒惰的星期六  阅读(4)  评论(0编辑  收藏  举报

Welcome to here

主页