最近在做一个服装网站的项目,用的是Eclipse,Svn,其中有一个增加功能,要上传图片都服务器上,
于是用到一个工具包代码如下:
public static String uploadFile(File inputFile, String fileName) {
//产生一个日期加五位随机数的文件名
SimpleDateFormat gs = new SimpleDateFormat("yyyyMMddHHmmss");
String time = gs.format(new Date());
String imageFileName = time + getRandom() + getExtention(fileName);
//获取项目名
String sp = ServletActionContext.getRequest().getContextPath();
String spath = sp.substring(1, sp.length());
// 获取目标地址
String[] str = ServletActionContext.getServletContext().getRealPath("/").split(".metadata");
File imageFile = new File(str[0] + spath + "\\Webroot\\UploadImages\\"+ imageFileName);
String imageSrc = imageFile.getPath();
ServletActionContext.getRequest().setAttribute("fileName",imageFile.getPath());
//上传文件,
copy(inputFile, imageFile);
return imageSrc;
}就是在目标服务器重新生成一个日期+5位随机数的文件,但数据库中地址那个字段显示的是:E:\Workspace\ctcs11\Webroot\UploadImages\2009081915322682855.jpg,我的项目Workspace在E盘,我想当用户通过浏览器访问的是他本地的E:\Workspace\ctcs11\Webroot\UploadImages\2009081915322682855.jpg,肯定是找不到的,有什么可以改正的。
还有我们组的workspace都不统一,所以数据库中的地址也是乱七八糟的有D盘的,有E盘的。
于是用到一个工具包代码如下:
public static String uploadFile(File inputFile, String fileName) {
//产生一个日期加五位随机数的文件名
SimpleDateFormat gs = new SimpleDateFormat("yyyyMMddHHmmss");
String time = gs.format(new Date());
String imageFileName = time + getRandom() + getExtention(fileName);
//获取项目名
String sp = ServletActionContext.getRequest().getContextPath();
String spath = sp.substring(1, sp.length());
// 获取目标地址
String[] str = ServletActionContext.getServletContext().getRealPath("/").split(".metadata");
File imageFile = new File(str[0] + spath + "\\Webroot\\UploadImages\\"+ imageFileName);
String imageSrc = imageFile.getPath();
ServletActionContext.getRequest().setAttribute("fileName",imageFile.getPath());
//上传文件,
copy(inputFile, imageFile);
return imageSrc;
}就是在目标服务器重新生成一个日期+5位随机数的文件,但数据库中地址那个字段显示的是:E:\Workspace\ctcs11\Webroot\UploadImages\2009081915322682855.jpg,我的项目Workspace在E盘,我想当用户通过浏览器访问的是他本地的E:\Workspace\ctcs11\Webroot\UploadImages\2009081915322682855.jpg,肯定是找不到的,有什么可以改正的。
还有我们组的workspace都不统一,所以数据库中的地址也是乱七八糟的有D盘的,有E盘的。
sorry,刚做项目,对一些东西还不太了解,我想知道那目标地址应该怎么写
String fileDirectory = request.getSession().getServletContext().getRealPath("/")+ filePath;
ServletActionContext.getServletContext().getRealPath("/").输出都一样
E:\Workspace\ctcs11\Webroot\UploadImages\2009081915322682855.jpg2.保存完成后 其他机器需要访问 所以图片的路径就不能是绝对路径了
就应该写成
192.168.*.*/Webroot\UploadImages\2009081915322682855.jpg 了 这样其他机器就可以访问了原理就是这样 如果方法不会写 就加我qq:315689376