首先为FileController添加Mapping
@RequestMapping(value = "/file/compress/{name}.{suffix}")
public void downloadFileCompress(HttpServletRequest request, HttpServletResponse response, @PathVariable String name, @PathVariable String suffix){
log.info("File:收到文件下载请求");
OutputStream out = null;
try {
String fileName = name + "." + suffix;
//用hash算法得出存储路径
int hashcode = fileName.hashCode();
int dir1 = hashcode & 0xf;
int dir2 = (hashcode & 0xf0) >> 4;
//拼接文件路径
String resultPath = ResourceUtils.getFile("").getAbsolutePath() + "/Upload/" + dir1 + "/" + dir2 + "/";
log.info("File:文件保存路径为:" + resultPath);
File targetFile = new File(resultPath, fileName);
if(targetFile.exists()) {
log.info("File:开始文件传输");
out = response.getOutputStream();
ImageCompressUtil.compressToOutputStream(targetFile, out); //将
} else log.info("File:文件不存在");
}catch (Exception e) {
e.printStackTrace();
log.info("File:文件输出发生错误");
} finally {
log.info("File:文件传输成功");
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
添加ImageCompressUtil并实现文件压缩代码
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
public class ImageCompressUtil {
public static void compressToOutputStream(File targetFile, OutputStream out) {
InputStream in = null;
BufferedImage src = null;
try {
int threshold = 1024 * 1024;
if (targetFile.length() > threshold) {
BigDecimal rate = new BigDecimal(Math.sqrt(new BigDecimal(threshold).divide(new BigDecimal(targetFile.length()), 10, BigDecimal.ROUND_HALF_UP).doubleValue()));
in = new FileInputStream(targetFile);
src = ImageIO.read(in);
int width = new BigDecimal(src.getWidth()).multiply(rate).intValue();
int height = new BigDecimal(src.getHeight()).multiply(rate).intValue();
BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
target.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
ImageIO.write(target, "jpg", out);
} else {
in = new FileInputStream(targetFile);
byte[] temp = new byte[1024];
while(in.read(temp) != -1) out.write(temp);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
ImageCompressUtil将文件直接输出到OutputStream中,完成图片传输