这样一旦某个Request是一个MultipartRequest,它就会首先被MultipartResolver处理,然后再转发相应的Controller。
在UploadImageController中,将HttpServletRequest转型为MultipartHttpServletRequest,就能非常方便地得到文件名和文件内容:
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 转型为MultipartHttpRequest:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获得文件:
MultipartFile file = multipartRequest.getFile("file");
// 获得文件名:
String filename = file.getOriginalFilename();
// 获得输入流:
InputStream input = file.getInputStream();
// 写入文件...
}
生成缩略图
当用户上传了图片后,必须生成缩略图以便用户能快速浏览。我们不需借助第三方软件,JDK标准库就包含了图像处理的API。我们把一张图片按比例缩放到120X120大小,以下是关键代码:
public static void createPreviewImage(String srcFile, String destFile) {
try {
File fi = new File(srcFile); // src
File fo = new File(destFile); // dest
BufferedImage bis = ImageIO.read(fi);
int w = bis.getWidth();
int h = bis.getHeight();
double scale = (double)w/h;
int nw = IMAGE_SIZE; // final int IMAGE_SIZE = 120;
int nh = (nw * h) / w;
if( nh>IMAGE_SIZE ) {
nh = IMAGE_SIZE;
nw = (nh * w) / h;
}
double sx = (double)nw / w;
double sy = (double)nh / h;
transform.setToScale(sx,sy);
AffineTransformOp ato = new AffineTransformOp(transform, null);
BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
ato.filter(bis,bid);
ImageIO.write(bid, "jpeg", fo);
} catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed in create preview image. Error: " + e.getMessage());
}
}
文章来源于领测软件测试网 https://www.ltesting.net/