后端文件上传(图片)
引入缩略图依赖
<!--缩略图相关依赖-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
后台接口代码
上传
import com.wuxiapptec.uniteplatform.rest.modular.domain.util.Encodes;
import com.wuxiapptec.uniteplatform.rest.modular.domain.util.Digests;
private static final String FILE_SEPARATOR = "/";
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<?> upload(@RequestPart("file") MultipartFile file) throws IOException {
log4.info("上传文件");
Map<String, String> result = new HashMap<>();
if (file.isEmpty()) {
log4.info("上传文件为空!");
result.put("msg","上传文件不能为空");
return new ResponseEntity<>(result, HttpStatus.NO_CONTENT);
}
String url = "";
try {
byte[] fileBytes = null;
try {
fileBytes = file.getBytes();
} catch (final IOException e1) {
e1.printStackTrace();
}
final String name = file.getOriginalFilename();
final String md5 = Encodes.encodeHex(Digests.md5(fileBytes));
StringBuilder path = getPath(md5);
path = path.append(name);
// 获取服务器文件资源保存路径(保存在数据库中)
String serverFileSavePath = settingMapper.getSetValue("FileSavePath");;
if (StringUtils.isEmpty(serverFileSavePath)) {
result.put("msg","服务器文件保存路径为空");
return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
}
String filePath = serverFileSavePath + FILE_SEPARATOR + path.toString();
File localFile = null;
try {
localFile = new File(filePath);
localFile.getParentFile().mkdirs();
Files.write(fileBytes,localFile);
} catch (final IOException e) {
log4.error("保存文件失败: {}", e);
}
url = fileSavePath + FILE_SEPARATOR + md5 + FILE_SEPARATOR + name;
// 缩略图名称添加固定后缀
int i = name.lastIndexOf(".");
String newName = name.substring(0,i) + "_thumbnail" + name.substring(i);
String path2 = serverFileSavePath + FILE_SEPARATOR + getPath(md5).toString() + newName;
// 按照一定比例生成缩略图
Thumbnails.of(localFile).scale(0.04f).outputQuality(1.0f).toFile(path2);
String zoomOutUrl = fileSavePath + FILE_SEPARATOR + md5 + FILE_SEPARATOR + newName;
// 返回原图和缩略图的url请求路径
result.put("url",url);
result.put("smallUrl",zoomOutUrl);
} catch (final Exception e){
log4.error("保存文件失败: {}", e);
new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(result, HttpStatus.OK);
}
/**
* 获取上传文件的路径
* @param md5
* @return
*/
private StringBuilder getPath(String md5) {
final StringBuilder sb = new StringBuilder();
// @formatter:off
sb.append(StringUtils.left(md5, 2))
.append(FILE_SEPARATOR)
.append(StringUtils.mid(md5, 2, 2))
.append(FILE_SEPARATOR)
.append(md5)
.append(FILE_SEPARATOR);
// @formatter:off
return sb;
}
下载
import java.net.URLEncoder;
/**
* 获取文件
*
* @param p
* @param name
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/{p}/{name:.+}", method = RequestMethod.GET)
public void download(@PathVariable("p") String p, @PathVariable("name") String name, HttpServletRequest request,
HttpServletResponse response) throws IOException {
log4.info("文件资源获取");
// get absolute path of the application
final ServletContext context = request.getServletContext();
final String appPath = context.getRealPath("");
System.out.println("appPath = " + appPath);
// construct the complete absolute path of the file
final String fullPath = p + "/" + name;
// 调用service解析请求路径获取对应文件
final File downloadFile = fileService.downloadFile(fullPath);
final FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
final String headerKey = "Content-Disposition";
String fileName = URLEncoder.encode(downloadFile.getName(),"UTF-8");
final String headerValue = String.format("attachment; filename=\"%s\"",
fileName);
response.setHeader(headerKey, headerValue);
// get output stream of the response
final OutputStream outStream = response.getOutputStream();
IOUtils.copy(inputStream, outStream);
inputStream.close();
outStream.close();
}
service解析路径
import org.apache.commons.lang3.time.DateUtils;
private static String[] parsePatterns = {"yyyy-MM-dd","yyyy年MM月dd日",
"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyyMMdd","yyyyMMddHHmmss"};
/**
* 下载文件
* @param path
* @return
* @throws IOException
*/
public File downloadFile(String path) throws IOException {
final String[] paths = path.split("/");
final String p3 = paths[0];
final String name = paths[1];
final String p1 = StringUtils.left(p3, 2);
final String p2 = StringUtils.mid(p3, 2, 2);
// 获取服务器文件资源保存路径
String fileSavePath = "";
StringBuilder sb;
try {
// 根据不同的业务情况解析路径,获取文件的保存路径
if (p3.contains("-")) {
String[] tempPath = p3.split("-");
fileSavePath = settingMapper.getSetValue("ImportModule");
sb = new StringBuilder(fileSavePath).append(File.separator).append(tempPath[0]).append(File.separator)
.append(tempPath[1]).append(File.separator).append(name);
} else {
// 如果是日期格式则是excel
DateUtils.parseDate(p3, parsePatterns);
fileSavePath = settingMapper.getSetValue("ExcelSavePath");
sb = new StringBuilder(fileSavePath).append(File.separator).append(p3).append(File.separator).append(name);
}
} catch (ParseException e) {
fileSavePath = settingMapper.getSetValue("FileSavePath");
sb = new StringBuilder(fileSavePath).append(File.separator).append(p1).append(File.separator).append(p2)
.append(File.separator).append(p3).append(File.separator).append(name);
}
final File file = new File(sb.toString());
return file;
}
ps:上述方法为当前业务案例,根据文件上传时的保存路径及返回的url,在下载时实现对应的解析,此处仍需完善
本文来自博客园,作者:喵师傅,转载请注明原文链接:https://www.cnblogs.com/wywblogs/articles/16095487.html