图片上传和图片加载

2018-07-18  本文已影响0人  简陌刀丶阿吉

第一种方式
图片上传和加载,是将图片上传到一个文件夹下,然后加载文件夹下的图片,

  /**
 * 
 * 上传图片
 * @param request
 * @param response
 * @param session
 * @param file
 * @return
 * @throws IllegalStateException
 * @throws IOException
 */
@RequestMapping("/uploadPhoto")
@ResponseBody
public String uploadImage(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam(value = "file", required = true) MultipartFile file)
        throws IllegalStateException, IOException {
    String pic_path = getConfigString("picture_path");
    Date date = new Date();
    long longTime = date.getTime();
    String fileName = longTime + String.valueOf((int)(Math.random() * 1000)) + ".png";
    File targetFile = new File(pic_path, fileName);
    if (!targetFile.exists()) {
        targetFile.mkdirs();
    }
    file.transferTo(targetFile);
    String fileUrl = fileName;
    return fileUrl;
}

/**
 * 
 * 读取图片
 * @param request
 * @param response
 * @throws IOException
 */
@RequestMapping(value = "/IMG")
public void image(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "No-cache");
    response.setDateHeader("Expires", 0);
    // 指定生成的响应图片,必须指定,否则错误.
    response.setContentType("image/jpeg");
    // 获取前台传过来图片路径
    String imagePath = request.getParameter("imagePath");
    imagePath = getConfigString("picture_path") + "\\"+ imagePath;
    // 输出文件
    FileInputStream io = new FileInputStream(imagePath);
    BufferedImage image = ImageIO.read(io);
    ImageIO.write(image, "png", response.getOutputStream());
    io.close();
}

    js代码 显示图片方式
    $('#show_img2').attr('src',zd_basePath + '/IMG?imagePath=' + data.tb);

第二种方式
是将图片上传到服务器的下面,同时将图片路径存储到数据库,在其余人调用的时候,只需要调用数据库中存储的路径就可以了。

    /**
 * 
 * 上传图片
 * @param file
 * @param request
 * @return
 * @throws IOException
 */
@RequestMapping("/uploadPhoto")
@ResponseBody
public String uploadImg(MultipartFile file, HttpServletRequest request) throws IOException {
    String path = System.getProperty("catalina.home") + "/webapps/images";
    String fileName = file.getOriginalFilename();
    Long timeStamp = System.currentTimeMillis();
    String ds = fileName.substring(fileName.lastIndexOf("."));
    File dir = new File(path, timeStamp + ds);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    file.transferTo(dir);
    String ip=getConfigString("server_ip");
    int port=Integer.parseInt(getConfigString("server_port"));
    String newpath = "http://" + ip + ":" + port + "/images/" + timeStamp + ds;
    return newpath;
}

  js代码  显示图片方式
  $('#show_img2').attr('src', data.tb);
上一篇下一篇

猜你喜欢

热点阅读