文件上传和下载
文件上传和下载是JAVA WEB中常见的一种操作,文件上传主要是将文件通过IO流传输到服务器的某一个特定的文件夹下;刚开始工作那会一个上传文件常常花费小半天的时间。自从有了springboot之后,简单到小学生都会的操作。废话不说,直接开始。
上传
上传操作进行封装,根据上传的文件,以及指定的文件路径保存到本地。
public class UploadUtil {
private static String projectPath = StringUtils.substringBefore(System.getProperty("user.dir").replaceAll("\\\\", "/"),"/");
/**
* 自定义上传路径和下载路径进行上传
* @param files 文件
* @param uploadPath 上传到路径
* @return
* @throws Exception
*/
public static Map<String, Object> upload(MultipartFile[] files, String uploadPath) throws Exception {
Map<String, Object> retMap = new HashMap<>();
if (files != null && files.length > 0) {
List<UploadVo> fileList = new ArrayList<>();
for (MultipartFile file : files) {
UploadVo entity = new UploadVo();
String fileName = file.getOriginalFilename();
String path = projectPath + uploadPath + fileName;
File dest = new File(path);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
entity.setName(fileName);
entity.setUrl(fileName);
fileList.add(entity);
}
retMap.put("data", fileList);
retMap.put("success", true);
} else {
retMap.put("data", null);
retMap.put("success", false);
}
return retMap;
}
}
下载
根据需要下载的文件路径,从本地获取相关文件进行下载。这里特别需要注意的是中文文件的乱码问题,否则容易导致下载到的文件格式以及名称会有不同。
题外话:
如果你想将资源分享的话,是可以通过这个原理,将你自己的文件夹及文件展示给别人下载哦。
public class DownloadUtil {
/**
* 按路径进行下载
* @param path
* @param request
* @param response
* @throws Exception
*/
public static void download(String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
Path file = Paths.get(path);
if (Files.exists(file)) {
String contentType = Files.probeContentType(Paths.get(path));
response.setContentType(contentType);
String filename = new String(file.getFileName().toString().getBytes("UTF-8"), "ISO-8859-1");
response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", filename));
response.setCharacterEncoding("UTF-8");
Files.copy(file, response.getOutputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
成果
效果欠佳,还望谅解
体验地址: http://120.79.226.4:8080/
下一次弄个类似百度网盘的上传下载的。