Springboot Http文件的访问 Url 转换 MultipartFile ,File 转 MultipartFile
pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
MyFileConvertUtil.java
/**
* @Author: JCccc
* @Date: 2022-8-25 02:15
* @Description:
*/
public class MyFileConvertUtil {
protected static final Logger logger = LoggerFactory.getLogger(MyFileConvertUtil.class);
/**
* Url 转换 MultipartFile
* @param url
* @param fileName
* @return
* @throws Exception
*/
public static MultipartFile urlToMultipartFile(String url, String fileName) throws Exception {
logger.info("开始 url 转换 MultipartFile,url={} ,fileName={}",url,fileName);
File file = null;
MultipartFile multipartFile = null;
try {
HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
httpUrl.connect();
logger.info("成功建立httpUrl连接"+httpUrl.toString());
file = inputStreamToFile(httpUrl.getInputStream(),fileName);
multipartFile = fileToMultipartFile(file);
httpUrl.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
logger.info("完成 url 转换 MultipartFile,url={} ,fileName={}",url,fileName);
return multipartFile;
}
/**
* InputStream 转 File
* @param ins
* @param fileName
* @return
* @throws Exception
*/
public static File inputStreamToFile(InputStream ins, String fileName) throws Exception{
logger.info("开始 InputStream 转换 File,fileName={}",fileName);
File file = new File(System.getProperty("java.io.tmpdir") + File.separator + fileName);
OutputStream os = new FileOutputStream(file);
int bytesRead;
int len = 8192;
byte[] buffer = new byte[len];
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
logger.info("完成 InputStream 转换 File,fileName={}",fileName);
return file;
}
/**
* File 转 MultipartFile
* @param file
* @return
*/
public static CommonsMultipartFile fileToMultipartFile(File file) {
logger.info("fileToMultipartFile文件转换中:"+file.getAbsolutePath());
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item=factory.createItem(file.getName(),"text/plain",true,file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return new CommonsMultipartFile(item);
}
}
使用简例:
@RequestMapping("/test")
public void test(@RequestParam String fileUrl) {
try {
File fileAuth = new File(fileUrl);
//原文件名
String sourceName = fileAuth.getName();
//自己起文件名
String newFileName="JCccc学Java文件名.xlsx";
MultipartFile file = MyFileConvertUtil.urlToMultipartFile(fileUrl, newFileName);
} catch (Exception e) {
e.printStackTrace();
}
}