srpingmvc 上传图片到服务器
文件上传要用到几个jar包:commens-io,commens FileUpload ,如果要跨服务器上传的话要用jersey-core和jersey-client
比较常见的文件上传组件有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。首先在
spring-mvc.xml配置文件中声明一个MultipartResolver:
这样一旦某个Request是一个MultipartRequest,它就会首先被MultipartResolver处理,然后再转发相应的Controller。
在相关上传文件接口中,将HttpServletRequest转型为MultipartHttpServletRequest,就能非常方便地得到文件名和文件内容,然后可以将文件内容
转为IO流进行存储或显示查看:
JavaCode部分:
1.获取上传详细内容
@Controller @RequestMapping("/upload") public class UploadController { @RequestMapping("uploadPic") public void uploadPic(HttpServletRequest request,String fileName,PrintWriter out){ //把Request强转成多部件请求对象 MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request; //根据文件名称获取文件对象 CommonsMultipartFile cm = (CommonsMultipartFile) mh.getFile(fileName); //获取文件上传流 byte[] fbytes = cm.getBytes(); //文件名称在服务器有可能重复? String newFileName=""; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); newFileName = sdf.format(new Date()); Random r = new Random(); for(int i =0 ;i<3;i++){ newFileName=newFileName+r.nextInt(10); } //获取文件扩展名 String originalFilename = cm.getOriginalFilename(); String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); //创建jesy服务器,进行跨服务器上传 Client client = Client.create(); //把文件关联到远程服务器 WebResource resource = client.resource(Commen.rephost+"/upload/"+newFileName+suffix); //上传 resource.put(String.class, fbytes); //ajax回调函数需要会写写什么东西? //图片需要回显:需要图片完整路径 //数据库保存图片的相对路径. String fullPath = Commen.rephost+"/upload/"+newFileName+suffix; String relativePath="/upload/"+newFileName+suffix; //{"":"","":""} String result="{\"fullPath\":\""+fullPath+"\",\"relativePath\":\""+relativePath+"\"}"; out.print(result); } }
2.生成缩略图
- 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());
- }
- }
以上就是用户在页面通过Form方式提交文件上传请求,然后MVC配置MultipartResolver拦截请求,使用MultipartHttpServletRequest将请求文件进行处理的相关步骤,非常的方便,写在这里