你的位置:首页 > Java教程

[Java教程]文件上传采用虚拟路径实现项目部署和用户资源分离


实现用户资源和项目分离使用到了下面这个工具类:

保存路径工具类
package cn.gukeer.common.utils;import com.github.pagehelper.StringUtil;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.core.io.ClassPathResource;import org.springframework.web.multipart.MultipartFile;import java.io.*;import java.util.Properties;import java.util.StringTokenizer;/** * 文件管理帮助类,处理应用之外的文件,如照片、邮件附件等不依赖于应用存在而存在的文件。 注意:里面的文件路径除了特殊说明外都是基于VFS根路径的 * * @author guowei */public abstract class VFSUtil {  private static Log log = LogFactory.getLog(VFSUtil.class);  /**   * VFS 根路径(最后没有/号)   */  private static String VFS_ROOT_PATH;  static {    try {      readVFSRootPath();// 给VFS_ROOT_PATH赋初始值    } catch (Exception e) {      log.error("读取配置文件出错!", e);    }  }  /**   * 读取VFS路径配置文件   */  private static void readVFSRootPath() {    String key = null;    if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {      key = "vfsroot.windows";    } else {      key = "vfsroot.linux";    }    try {      Properties p = new Properties();      InputStream inStream = new ClassPathResource("/db.properties").getInputStream();      p.load(inStream);      VFS_ROOT_PATH = p.getProperty(key);    } catch (Exception e1) {      VFS_ROOT_PATH = "";      log.error("[vfsroot路径读取]配置文件模式出错!", e1);    }    if (StringUtil.isEmpty(VFS_ROOT_PATH)) {      if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {        VFS_ROOT_PATH = "C:/gukeer/vfsroot/";      } else {        VFS_ROOT_PATH = "/opt/gukeer/vfsroot/";      }    }  }  /**   * 获取当前的VfsRootPath   *   * @return   */  public static String getVFSRootPath() {    return VFS_ROOT_PATH;  }  /**   * 获取文件输入流   *   * @param file   * @param fileStream   * @return   */  public static InputStream getInputStream(File file, boolean fileStream) {    if (fileStream == true) {//使用文件流      FileInputStream fin = null;      try {        fin = new FileInputStream(file);      } catch (FileNotFoundException e) {        if (log.isDebugEnabled()) {          log.debug(e);        }        String msg = "找不到指定的文件[" + file.getName() + "]。";        if (log.isDebugEnabled()) {          log.debug(msg);        }        throw new FileOperationException(msg, e);      }      return fin;    } else { // 使用内存流      InputStream in = null;      if (file != null && file.canRead() && file.isFile()) {        try {          ByteArrayOutputStream buffer = new ByteArrayOutputStream();          FileInputStream stream = new FileInputStream(file);          BufferedInputStream bin = new BufferedInputStream(stream);          int len = 0;          byte[] b = new byte[1024];          while ((len = bin.read(b)) != -1) {            buffer.write(b, 0, len);          }          stream.close();          in = new ByteArrayInputStream(buffer.toByteArray());        } catch (Exception e) {          String msg = "不能读取文件[" + file.getName() + "]";          if (log.isErrorEnabled()) {            log.error(msg, e);          }          throw new FileOperationException(msg, e);        }      } else {        String msg = "不是文件或文件不可读[" + file.getName() + "]";        if (log.isDebugEnabled()) {          log.debug(msg);        }        throw new FileOperationException("不是文件或文件不可读");      }      return in;    }  }}

注意事项:
  ①在resources文件夹内配置properties文件,包含vfsroot路径信息(windows和linux两个路径),修改上传方法使用户上传的文件和其他资源均存储在vfsroot路径下,并将图片存储路径保存在数据库内方便客户端读取使用;
  properties配置demo:
  
#db configjdbc.schema=gk_platformjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=falsejdbc.username=rootjdbc.password=123456vfsroot.windows=C:/platform/vfsroot/vfsroot.linux=/opt/platform/vfsroot/



  ②由于客户端不能直接请求访问位于服务器物理路径上的资源,因此前端页面采用流读取的方式显示图片和其他资源;在controller内添加如下方法:
  
  /**   * 读取图片文件   *   * @param response   * @throws Exception  */  @RequestMapping("/website/showPicture")  public void showPicture(HttpServletResponse response, String picPath) throws Exception {    File file = new File(VFS_ROOT_PATH + picPath);    if (!file.exists()) {      logger.error("找不到文件[" + VFS_ROOT_PATH + picPath + "]");      return;    }    response.setContentType("multipart/form-data");    InputStream reader = null;    try {      reader = VFSUtil.getInputStream(file, true);      byte[] buf = new byte[1024];      int len = 0;      OutputStream out = response.getOutputStream();      while ((len = reader.read(buf)) != -1) {        out.write(buf, 0, len);      }      out.flush();    } catch (Exception ex) {      logger.error("显示图片时发生错误:" + ex.getMessage(), ex);    } finally {      if (reader != null) {        try {          reader.close();        } catch (Exception ex) {          logger.error("关闭文件流出错", ex);        }      }    }  }



 

 前台jsp页面调用:<img src="<%=contextPath%>${image.imagesUrl}">,例如:

<img src='test/website/showPicture?picPath=/images/upload/image/20160608/1465355183063.png'/>

数据库保存图片的URL为/website/showPicture?picPath=/images/upload/image/20160608/1465355183063.png