文件上传
图片上传 使用 jquery的来异步提交,
使用jQuery第三方插件 jquer.form.js,
jsp的orm表单中要有enctype="multipart/form-data"
1、引入jar
2、springmvc.xml加入
<!-- 实现文件上传的配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="5242880"/>
</bean>
3、springmvc.xml加入 读取路径的配置
<mvc:resources mapping="/imgs/**" location="imgs/"></mvc:resources>
4、前台
4-1:jsp
注册一个onchange事件 οnchange="change()"
<form id="form13" action="<%=context_path%>点击上传的路径" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="picfile" οnchange="change()">
<img width="100" height="100" id="allimg" />
<input type="submit" value="上传">
</form>
4-2:js
function change() {
var opts = {
url:contextpath+"/ep/jxexamine/master/pictureupload",
type: "post",
dataType: "json",
success: function(data) {
$("#allimg").attr("src","${pageContext.request.contextPath}"+data.url);
}
};
$("#form13").ajaxSubmit(opts);
}
5.后台
@ResponseBody
@RequestMapping(value="pictureupload")
public void uploadImg(@RequestParam MultipartFile picfile,HttpServletRequest request,HttpServletResponse response) {
//编写图片上传的业务逻辑方法
//获取图片名称
String filename = picfile.getOriginalFilename();
//获取图片扩展名
String ext = filename.substring(filename.lastIndexOf(".")+1);
//生成图片名称
String imgName =UtilTools.getname();//自己写的一个获取字符串的方法作为图片名称
//生成图片的存放在服务器的路径
String path = "/imgs/"+imgName + "." + ext;
//获取服务器的绝对路径进行保存图片
String url = request.getSession().getServletContext().getRealPath("")+path;
//图片上传
try {
InputStream in = picfile.getInputStream();
OutputStream out = new FileOutputStream(new File(url));
byte[] b = new byte[1024];
int len;
while((len =in.read(b))!= -1) {
out.write(b, 0, len);
}
in.close();
out.close();
//把图片的路径使用json的格式进行返回
JSONObject jo = new JSONObject();
jo.put("path",path);
jo.put("url", path);
response.getWriter().write(jo.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
图片上传 的另外一种方法
@ResponseBody
@RequestMapping(value="/add.html",produces="text/html;charset=UTF-8",method=RequestMethod.POST)
public String add(@RequestParam("picpath1") MultipartFile picFile,Mobile mobile,
HttpServletRequest request,HttpSession session){
mobile.setId(IDUtils.genImageName());
mobile.setOntime(new Date());
String child=picFile.getOriginalFilename();
if (null!=child && !child.equals("")) {
try {
mobile.setPicpath(child);
String path=session.getServletContext().getRealPath("/upload");
File parent=new File(path);
if (!parent.exists()) {
parent.mkdir();
}
File descFile=new File(parent, child);
picFile.transferTo(descFile);//文件上传
} catch (Exception e) {
e.printStackTrace();
}
}
String path=request.getContextPath()+"/mobile/list.html";
if (mobileService.insertSelective(mobile)) {
return "<script>alert('添加成功');location.href='"+path+"'</script>";
}
return "<script>alert('添加成功');history.go(-1)</script>";
}
文件下载
前台js代码
Util.ajax({
url : contextpath + "/ep/data/mobile/list",
param : {
RESOURCE_ID : 此处为查询这款手机的id,
mapping : "getMobilesById"
},
success : function(data) {
if(data[0].picpath == undefined){
window.location.href = contextpath + "/ep/base/data/error"; //返回到找不到文件的页面
}else{
window.location.href =contextpath+"/ep/data/mobile/download?path="+data[0].picpath+"&name="+data[0].mobiletype;
}
}
});
后台代码
@RequestMapping(value = "download")
public String download(HttpServletRequest request,HttpServletResponse response) throws IOException{
String file_path=request.getParameter("path");
String ext = file_path.substring(file_path.lastIndexOf(".")+1);
//这里获取服务器的绝对路径。如果不会用的话,用下面注释掉的方法就可以
//String root = getServletContext().getRealPath("/");
//用下面的方法前,需要把HttpServletRequest request当做一个参数传递到本方法中,直接使用即可
String root = request.getSession().getServletContext().getRealPath("/");
String file_name=request.getParameter("name");
file_name=file_name+"."+ext; //如果文件名中有后缀 如.zip .jpg等 就不用这句话
String filepath=root+file_path;
File file = new File(filepath);
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.addHeader("Content-Disposition", "attachment;filename=" + new String(file_name.getBytes(), "ISO-8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
response.setContentType("application/octet-stream");
//这里的addHeader方法,如果报错,请使用下方注释掉的方法。
//response.addHeader("Content-Length", file.length());
//把第二个参数更改为String 类型即可
response.addHeader("Content-Length", String.valueOf(file.length()));
return null;
}