上传图片后用流预览图片

来源:互联网 发布:淘宝首页模板代码 编辑:程序博客网 时间:2024/05/21 17:28
主要是两个步骤,
1.上传图片到服务器
2.获取图片路径,attr到<img>预览
先上一段后台代码
@RequestMapping(value = "comparison/upload", method = RequestMethod.POST)@ResponseBodypublic String upload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request) throws IOException {    //String pathRoot = request.getSession().getServletContext().getRealPath("");  获得物理路径webapp所在路径    String path="";    if(!file.isEmpty()){        //生成uuid作为文件名称        String uuid = UUID.randomUUID().toString().replaceAll("-","");        //获得文件类型(可以判断如果不是图片,禁止上传)        String contentType=file.getContentType();        //获得文件后缀名称        String imageName=contentType.substring(contentType.indexOf("/")+1);        path="D:/springUpload/"+uuid+"."+imageName;        file.transferTo(new File(path));    }    return path;}/** * 根据图片的地址,返回图片的缓冲流 * @param path * @return */public static BufferedImage getInputStream(String path){    try {        String imgPath = path;        BufferedImage image = ImageIO.read(new FileInputStream(imgPath));        return image;    } catch (Exception e) {        e.printStackTrace();        System.out.println();        System.out.println("获取图片异常:java.awt.image.BufferedImage");        System.out.println("请检查图片路径是否正确,或者该地址是否为一个图片");    }    return null;}/** * 根据图片的地址,来获取图片 * @param path * @param response */@ResponseBody@RequestMapping("comparison/getImg")public void getImg(@RequestParam("path")String path,HttpServletResponse response){    BufferedImage img = new BufferedImage(300, 150, BufferedImage.TYPE_INT_RGB);    img = getInputStream(path);    if(img==null){        throw new RuntimeException("打印图片异常:com.controller.Business_Ctrl.getImg(String, HttpServletResponse)");    }    if(img!=null){        try {            ImageIO.write(img, "JPEG", response.getOutputStream());        } catch (IOException e) {            e.printStackTrace();            System.out.println("打印异常:com.controller.Business_Ctrl.getImg(String, HttpServletResponse)");        }    }}
html代码:
<form name="upload_form" action="upload" method="post" enctype="multipart/form-data">   <input name="file" type="file" style="display: none;"/></form>
<img id="image-right" width="100%" height="100%"/>

js代码:
$(this).parent().ajaxSubmit(function(data){   $("#image-right").attr("src","getImg?path="+data+"");});

原创粉丝点击