最近在做一个后台系统,需要给用户添加照片,但由于是用的ssm框架以前的图片上传类不能使用,翻来覆去弄了8-9个小时,在借助度娘和csdn博客上各位大神的情况下终于成功了,把过程记录下来分享给大家,希望能对大家有所帮助
1.准备jar包,js
maven项目在导入ssm框架的包的时候IDE(eclipse,IDEA...)会自动帮你导入,如果没有请自行导入
和Jquery一样需要引入到你的页面
2.配置springMvc
<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 最大内存大小 -->
<property name="maxInMemorySize" value="10240"/>
<!-- 最大文件大小,-1为不限制大小 -->
<property name="maxUploadSize" value="-1"/>
</bean>
添加bean到你的spring配置文件中
3.编写图片上传的工具类(你也可直接写到Controller中,但为了方便使用我们把它封装起来)
package com.wz.util;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class UploadImageUtil {
public static String PATH="../../webapps/uploadFiles";//上传的图片存放位置
String fileName=null; //文件名
public String upload(CommonsMultipartFile file,HttpSession session){
String curProjectPath = session.getServletContext().getRealPath("/");
String saveDirectoryPath = curProjectPath + PATH;
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);//获取文件后缀名
File saveDirectory = new File(saveDirectoryPath);
if(!file.isEmpty()){//如果文件不为空
fileName = System.currentTimeMillis()+new Random().nextInt(10000)+"_apicture"+"."+suffix; //随机生成一个文件名
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(saveDirectoryPath,fileName));//存入目标路径
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "../uploadFiles"+"/"+fileName; //返回存入数据库的路径
}
}
PATH:为你的tomcat存放静态资源路径的位置 一般是你所安装的tomcat目录下webapps文件中,创建uploadFiles文件夹方便管理,当你的项目发布到tomcat上时便可以直接浏览到服务器的静态资源,获取方式如下:
curProjectPath:这是获取到你前台传过来的图片的绝对路径,tomcat会把它放到 X:\apache-tomcat-xx.xx\wtpwebapps\你的项目 目录下(在我的电脑上是如此,如果不同可以自己去把它输出到后台辨别),所以我们通过 ../../ webapps 的path把它放入
webapps中
可自行添加逻辑带码来完成文件类型上传的限制
3.1 controller类
@RequestMapping("add.action")
@ResponseBody
public JsonMode addAdmin(@RequestParam("apicture") CommonsMultipartFile file,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
JsonMode jsonMode = new JsonMode();
upload = new UploadImageUtil();
String apicture = upload.upload(file,session); //获取存到数据库的图片路径
int result = adminBiz.addAdmin(apicture);
System.out.println(result);
if(result>0){
jsonMode.setCode(1);
}else{
jsonMode.setCode(0);
}
return jsonMode;
}
@RequestParam("apicture") CommonsMultipartFile file :获取到前台传来的图片文件流参数,@RequestParam注解内参数要与from表单内<input type="file"> name属性一致
4.发ajax请求
$.ajaxFileUpload({
url:"../../add.action",
secureuri:false,
fileElementId:"admin_add_photo",
dataType:"json",
enctype:"multipart/form-data",
success:function(data){
if(data.code==1){
$.messager.show({title:"成功提示",msg:"信息添加成功...",timeout:2000,showType:"slide"});
}else{
$.messager.alert("失败提示","信息添加失败...","error");
}
},
});
fileElementId:需要和你的input id一致
需要注意的是:
enctype:"multipart/form-data",
这个属性必须要添加上去,不然spring mvc会拦截你发送的文件流
那么至此文件便可以成功发送了,如果你想要接收到服务器返回的数据那么你还需要修改一下ajaxFileUpload.js中的uploadHttpData方法,因为它会自动给你返回的json数据加上<pre>标签
修改后的uploadHttpData方法:
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" ){
jQuery.globalEval( data );
}
// Get the JavaScript object, if JSON is used.
if ( type == "json" ){
data = jQuery.parseJSON(jQuery(data).text());
}
// evaluate scripts within html
if ( type == "html" ){
jQuery("<div>").html(data).evalScripts();
}
if(type=="text"){
return data;
;
}
return data;
}