1,上传相关的配置信息
2,controller获取图片信息
@RequestMapping("/imagelist.json")
@ResponseBody
public Object uploadImage(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "uploadImage", required = false) MultipartFile multipartFile) throws IOException {
//使用UUID给图片重命名,并去掉四个“-”
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String dateNowStr = sdf.format(d);
String name = UUID.randomUUID().toString().replaceAll("-", "");
//获取文件的扩展名
String ext = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
//设置图片上传路径
// String url = request.getSession().getServletContext().getRealPath("statics/upload/" + dateNowStr);
String url = "/usr/local/upload/images/" + dateNowStr;
File file = new File(url);
if (!file.exists()) {
file.mkdirs();
}
//以绝对路径保存重名命后的图片
multipartFile.transferTo(new File(url + File.separator + name + "." + ext));
//把图片存储路径保存到数据库
//System.out.println("保存前的路径:" + File.separator + "statics" + File.separator + "upload" + File.separator + dateNowStr + File.separator + name + "." + ext);
System.out.println("保存前的路径:" + url + File.separator + name + "." + ext);
//重定向到查询所有用户的Controller,测试图片回显
Map map = new HashMap();
map.put("urlpath", File.separator + "statics" + File.separator + "upload" + File.separator + dateNowStr + File.separator + name + "." + ext);
map.put("imageId", request.getParameter("imageId"));
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
String result = JSONObject.fromObject(map).toString();
// out.print("<script>parent.callback('" + result + "');</script>");
return result;
}
其中:
String url = "/usr/local/upload/images/" + dateNowStr;
/usr/local/upload/images未Linux上的文件夹,我们将所有图片都上传到此目录。
往数据库怎么存图片路径??
<img src="/images/2018-11-27/e3726fb1b69c487b90fc96da7556fcbf.png">
我们需要的是这样一个图片路径就可以了,所以我们往数据库存值:
/images/2018-11-27/e3726fb1b69c487b90fc96da7556fcbf.png
现在问题来了,怎么能获取到本地路径里的图片呢?
解决办法:
使用虚拟路径来配置,在tomcat下的server.xml中增加一个代码 在<Host></Host>中间:
<Context docBase="/usr/local/upload/images" path="/images" reloadable="true"/>
然后在JSP页面中<img src = "/images/(图片名)">就可以访问图片了。
ok======