在日常开发过程中,文件的上传下载是最常用的功能,通常我们需要把文件上传到某个特定的影像平台,由平台统一管理文件,当我们需要时,则从平台下载
文件上传
1.上传到本地指定路径 file.transferTo()
2.hutool中的HttpUtil上传到指定的url
@Slf4j
public class UploadUtil{
/**
* 上传方式一
* 上传到指定路径
* @param file 上传的文件
* @param savePath保存的路径
*/
public static File uploadToPath(MultipartFile file, String savePath) throws Exception {
if(file == null) {
throw new Exception("未找到上传文件!");
}
if(savePath == null || "".equals(savePath.trim())) {
throw new Exception("上传文件失败:未找到文件存放路径!");
}
String fileName = file.getOriginalFilename();
//创建存放目录
File saveFiles=new File(savePath);
if(!saveFiles.exists()){
saveFiles.mkdirs();//创建文件夹,如果上级目录不存在,则挨个创建目录
}
//指定需要保存的文件名称和路径
File saveFile = FileUtil.newFile(savePath + File.separator + fileName);
try {
file.transferTo(saveFile);//保存文件到指定目录
//FileUtil.writeBytes(file.getBytes(), saveFile);
} catch (Exception e) {
log.error("文件保存到临时目录失败!" + e.getMessage());
}
return saveFile;
}
/**
* 上传方式二
* 上传到指定url
* @param multipartFiles 需要上传的文件
* @param baseUrl 上传的远程地址
*/
public static JSONObject uploadByUrl(MultipartFile[] multipartFiles,String baseUrl) throws Exception {
if (multipartFiles == null || multipartFiles.length == 0) {
throw new Exception("未选择文件");
}
// MultiResource 多资源组合资源 此资源为一个利用游标自循环资源,只有调用next() 方法才会获取下一个资源,使用完毕后调用reset()方法重置游标
MultiResource multiResource = new MultiResource(
Arrays.stream(multipartFiles)
.map(multipartFile -> {
try {
return new InputStreamResource(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
} catch (Exception ex) {
// log.error("读取io流异常", ex);
throw new SystemException("读取io流异常!");
}
}).collect(Collectors.toList())
);
HttpResponse execute = HttpRequest.post(baseUrl + "/uploadFiles/")
.form("files", multiResource)
.execute();
return JSONObject.parseObject(execute.body());
}
}
两种方式的文件下载
根据影像平台url下载并实时返回给前端,也可以通过配置在代码中的文件路径去下载
另外hutool的HttpUtil工具类有下载文件的方法downloadFile、downloadFileFromUrl等
@Slf4j
public class FileUtils{
/**
* 下载方式一
* 根据影像地址下载文件
* @param downloadUrl 下载地址
* @param fileName 文件名
* @param response 包含返回给前端的影像内容
*/
public static void downloadByUrl(String downloadUrl, String fileName, HttpServletResponse response) {
log.info("文件目标下载地址:[{}], 文件名称:[{}]", downloadUrl, fileName);
InputStream input = null;
OutputStream output = null;
try {
output = response.getOutputStream();//写入影像
URL url = new URL(downloadUrl);
URLConnection urlConn = url.openConnection();
urlConn.setDoInput(true);
input = urlConn.getInputStream();//根据地址读取影像文件
response.reset();
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + transferToNormal(fileName));
response.setContentType("application/octet-stream");
byte[] b = new byte[1024];
int len = 0;
while ((len = input.read(b)) > 0) {
output.write(b, 0, len);
}
output.flush();
} catch (Exception e) {
log.error("从影像平台下载文件失败,信息:{}", e.getMessage());
} finally {
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (IOException e) {
log.error("io流关闭异常,信息:{}", e.getMessage());
}
}
}
/**
* 下载方式二
* 从文件路径下载
* @param filePath 请求的路径
* @param response 包含返回给前端的影像内容
*/
public static void downloadByPath(String filePath, HttpServletResponse response) {
//FileUtil是hutool的文件工具类
File newfile =FileUtil.newFile(filePath);
if (!newfile.exists()) {
throw new Exception("没有找到要下载的文件,请检查文件路径!");
}
//取得文件名
String fileName = newfile.getName();
InputStream fis = null;
OutputStream out = null;
try {
fis = new FileInputStream(newfile);
out = response.getOutputStream();
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
response.setHeader("Content-Length", String.valueOf(newfile.length()));
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
out.write(b, 0, len);
}
out.flush();
} catch (Exception e) {
log.info("从文件路径下载文件失败,异常信息:{}", e.getMessage());
} finally {
try {
if (fis != null) {
fis.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
log.info("close异常!异常信息:{}", e.getMessage());
}
}
}
}