实现图片上传
用户必须可以上传图片,所以须要文件上传的功能。比较常见的文件上传组件有Commons FileUpload(http://jakarta.apache.org/commons/fileupload/a>)和COS FileUpload(http://www.servlets.com/cos),Spring已经彻底集成了这两种组件,这里咱们选择Commons FileUpload。
因为Post一个包含文件上传的Form会以multipart/form-data请求发送给服务器,必须明确告诉DispatcherServlet如何处理MultipartRequest。首先在dispatcher-servlet.xml中声明一个MultipartResolver:java
xml 代码web
<bean id="multipartResolver" spring
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> apache
<!-- 设置上传文件的最大尺寸为1MB --> 服务器
<property name="maxUploadSize"> spa
<value>1048576</value> orm
</property> xml
</bean> 图片
这样一旦某个Request是一个MultipartRequest,它就会首先被MultipartResolver处理,而后再转发相应的Controller。
在UploadImageController中,将HttpServletRequest转型为MultipartHttpServletRequest,就能很是方便地获得文件名和文件内容:ip
java 代码
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();
// 写入文件
// 或者:
File source = new File(localfileName.toString());
multipartFile.transferTo(source);
}
生成缩略图 (目录)
当用户上传了图片后,必须生成缩略图以便用户能快速浏览。咱们不需借助第三方软件,JDK标准库就包含了图像处理的API。咱们把一张图片按比例缩放到120X120大小,如下是关键代码:
java 代码
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());
}
}