您的位置:首页 > 其它

SSH框架搭建电商系统之图片上传与显示

2017-04-18 13:41 274 查看
1.从Jsp页面提取上传的图片信息upload,<s:from>里要加 enctype="multipart/form-data"属性,上传的图片name="upload" type="file"

2.图片上传到指定路径(其中我上传的是到服务器下文件夹,并保存路径为image/products/***)

private String imageFileName;
private String imageContentType="jpg";
public String save() throws IOException{

//上传封面图片到服务器
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = formatter.format(currentTime);
imageFileName = dateString;
String realpath = "G:\\WorkPlace\\shop\\WebRoot\\images\\products"; //可更换
System.out.println("realpath:"+realpath);
if(upload!=null){
File savefile = new File(new File(realpath),imageFileName+"."+imageContentType);
if(!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
FileUtils.copyFile(upload,savefile);
ActionContext.getContext().put("message", "上传文件成功");
String path = "images/products/";
path += imageFileName;
path += "."+imageContentType;
product.setCover(path);
System.out.println(product.getCover());
}
return NONE;


文件名为当前日期时间+随机数生成

/**
*
* @方法说明  生成文件名称
* @createDate 2016-5-15
*/
public static String createImageName() {
//根据时间生成文件名
SimpleDateFormat sdf = new SimpleDateFormat("ddHHmmssS");
String fileName = sdf.format(new Date());

//加上随机数,防止重复
Random rand = new Random();
fileName += String.valueOf(rand.nextInt(100));

return fileName;
}

public static void main(String[] args) {
createImageName();
}

}


此时数据库cover里储存了文件路径。

3.调用图片路径

<img alt="" src="${ pageContext.request.contextPath }/<s:property value="#e.Product.cover"/>" />
↑这里我直接保存的image/*** 路径
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: