加上传图片功能,
首先添加依赖:
我们的form标签中必须要加:enctype=”multipart/form-data”
其次使用的是springmvc,我们需要在springmvc的xml配置中添加下面配置:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- set the max upload size100MB -->
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>
接下来,进入后台图片的相关处理,这里我封装了一个图片上传util:
/**
* 处理文件上传方法封装(单张图片)
* @param imageFile
* @param request
* @return
* @throws Exception
*/
public static String fileUpload(MultipartFile imageFile,HttpServletRequest request) throws Exception{
String fileName = null;
if(!imageFile.isEmpty()){
//获取项目跟路径
String filePath = request.getServletContext().getRealPath("/");
//获取项目名
String projectName = request.getContextPath();
//将项目跟路劲下的项目名称置为空,因为图片需要在项目外的webapp下面存放,sub截取下标为1的字符
filePath=filePath.replace(projectName.substring(1),"");
System.out.println(filePath);
//重新生成文件名字
fileName = DateUtil.getCurrentDateStr()+"."+imageFile.getOriginalFilename().split("\\.")[1];
//将文件保存到指定目录
imageFile.transferTo(new File(filePath+"staticimage/"+fileName));
}
//返回文件名字供保存
return fileName;
}
然后我们直接调用即可:
/**
* 处理图片上传
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/upload")
public String upload(@RequestParam("myFileName") MultipartFile imageFile,HttpServletRequest request,HttpServletResponse response)throws Exception{
System.out.println("开始处理");
String fileName = FileUploadUtil.fileUpload(imageFile, request);
// HttpSession session = request.getSession();
// session.setAttribute("imageSession", fileName);
//定义前台访问路径
ResourceBundle resource = ResourceBundle.getBundle("config");
String path = resource.getString("imageUrl");
JSONObject json = new JSONObject();
//持久化图片操作
UserImg userImg = new UserImg();
userImg.setImage(path+fileName);
int total = userImgService.add(userImg);
System.out.println(total);
json.put("imgUrl", path+fileName);
json.put("img", fileName);
ResponseUtil.write(response, json);
return null;
}
ResourceBundle resource = ResourceBundle.getBundle(“config”);这个是我写的一个静态资源路径,指向webapp下:imageUrl=http://127.0.0.1:8080/staticimage/
在这里解释为什么要放在webapp下面,1:、管理起来方便,项目重新部署无需备份;2、如果放在项目中,项目重新部署,资源文件将消失。因为项目重新编译生成的文件是一份新的,编译并不会进行文件等上传,所以会覆盖掉原先。所以放在项目以外的地方相对安全。其次,说明问题,eclipse中项目默认部署在他的插件里面,也就是eclipse.me什么的,不是我们自己的tomcat,所以首先删掉tomcat,重新添加,
在没添加项目之前可以修改。
好了,这里上传图片就搞定了。但是前台访问我们还需要在tomcat的conf–>Catalina–>localhost下,新建一个文件,我这里是staticimage.xml,因为我把资源文件放在了webapp下面的staticimage这个文件夹。staticimage.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<Context docBase="D:\work\Tomcat\apache-tomcat-7.0.32\webapps\staticimage" reloadable="true"> </Context>
前台访问的话src=”/staticimage/(这儿是我们图片的名字)”
缺少的东西后期想起来会有补充。