实现原理:
前台通过input标签的file属性上传到后台,后台读取图片文件,将其存储在项目内部文件夹中,最后再将图片名存入到数据库中。
具体实现:
首先,要实现前台图片上传,必须要在form表单上设置method="post" 和enctype="multipart/form-data",并将图片上传的input标签的type选为file属性。具体实现代码如下
<form action="/ticketWeb/hotel/insertHotelInformation.do" method="post" enctype="multipart/form-data" >
<table>
<caption><b>酒店数据管理</b></caption>
<tr>
<td><input type="file" name="hotelimage" accept="image/gif, image/jpeg, image/png, image/jpg"></td>
</tr>
<tr>
<td><input type="submit" value="发布" ></td>
</tr>
</table>
</form>
接着,我们得先配置两个jar包,commons-fileupload和commons-io以用来处理上传到springmvc的图片,我是通过maven来导入jar包的,这是maven的代码段:
<!-- 上传图片的包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- 上传图片的包 -->
然后,上传spring的准备工作完成了,首先,我要在bean里面加一个MultipartFile类型的图片属性,用来存放上传到springmvc的图片文件,同时,加一个String类型的属性,用来存储图片名称(图片名称到时候使用UUID以保证不会重复)。这是我的javabean代码段:
private MultipartFile hotelimage;
private String hotelimagepath;
接着,这是springmvc的代码,主要是获取图片到我自定义的hotel的javabean中,然后将图片放到ImageService的方法中进行真正处理图片。
@RequestMapping("insertHotelInformation")
public String insertHotelInformation(Hotel paramHotel,HttpServletRequest request,Model model) throws ParseException, IllegalStateException, IOException{
if(paramHotel!=null){
hotel=paramHotel;
//获取本项目内部的源路径
String path=request.getSession().getServletContext().getRealPath("");
//处理图片的方法,入参为项目源路径和图片文件,并返回图片名称。
String imagepath=ImageService.imageSave(hotel.getHotelimage(),path);
//将图片名称存入到数据库中
hotel.setHotelimagepath(imagepath);
boolean b=hs.insertHotelInformation(hotel);
if(b){
return "html/mainFrame";
}
}
return "html/error";
}
接下来就是真正处理图片的ImageService的实现代码,它先将图片使用UUID命名为不会被重复的名称,然后,它将图片存储到项目内部中,最后返回图片名称,具体代码如下:
public class ImageService {
//保存图片,并且返回图片路径
public static String imageSave(MultipartFile image,String path) throws IllegalStateException, IOException{
//保存数据库的路径
String sqlPath = null;
//定义文件保存的本地路径
String localPath=path+"static/imgs/loadimgs/";
//定义 文件名
String filename=null;
if(!image.isEmpty()){
//生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-","");
//获得文件类型(可以判断如果不是图片,禁止上传)
String contentType=image.getContentType();
//获得文件后缀名
String suffixName=contentType.substring(contentType.indexOf("/")+1);
//得到 文件名
filename=uuid+"."+suffixName;
System.out.println(filename);
sqlPath = localPath+filename;
System.out.println(sqlPath);
//文件保存路径
image.transferTo(new File(sqlPath));
}
//把图片的相对路径保存至数据库
return filename;
}
}
最后,返回springmvc的controller中,将图片名称存储到数据库中,这个是常规操作,这里就不多加描述了,这就是基于form表单的单图片上传方式 ,存储图片位置放在项目内部,数据库存储的是图片名称。