MultipartFile上传/下载图片
文件上传
图片上传 使用 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; }
MultipartFile上传/下载图片相关推荐
- 使用GridFS上传下载图片以及其他文件
MongoDB所带的GridFS是极为方便的文件管理系统,MongoDB的Shell语言与Python的语言风格非常像,写起来非常方便.重点是需要用StringIO将文件装换为二进制保存.主程序是一个 ...
- FTP数据抓包上传下载图片(wireshark)
一.搭建本地FTP服务器 1.在D盘创建"kiss_ftp"文件夹,将gg.jpg保存到该文件夹下. 2.打开FTP服务器软件,设置用户名为"kiss",密码为 ...
- im4java裁剪图片之后再将图片在mongoDB上传下载图片
本文主要实现以下几个功能: 1.先通过IM4java的功能将本地的一张图片剪切出来形成新的图片 2.通过上传功能,将裁剪的图片上传到mongodb数据库中储存 3.再从mongodb数据库中取出刚才上 ...
- java读取服务器图片大小,SpringMVC中MultipartFile上传获取图片的宽度和高度详解
SpringMVC一般使用MultipartFile来做文件的上传,通过MultipartFile的getContentType()方法判定文件的类型(MIME) ".doc":& ...
- java公众号图片上传_java微信公众号上传下载图片,springmvc demo
[实例简介] 微信上传下项目使用说明: 1.本项目适合学习springmvc学者(springmvc demo), url(http://localhost:8082/com.demo.weixin/ ...
- SpringBoot 利用MultipartFile上传本地图片生成图片链接
方法一 实现类: public String fileUpload(MultipartFile file) {if(file == null){return null;}String fileName ...
- 微信小程序系列——上传下载图片以及图片的展示
一.上传 wxml: <button bindtap='upload'>上传文件</button> js: 首先在data里添加全局变量images data: {images ...
- C# webapi 上传下载图片
客户端上传文件 string url = url + "webUploadFile";Uri server = new Uri(url);HttpClient httpClient ...
- Android图片上传和下载,android 上传/下载 图片
public class HttpAssist { private static final String TAG = "uploadFile"; private static f ...
最新文章
- 省选专练(学习)可持久化Trie树(BZOJ3261)
- python在线读-用python实现自己的小说阅读器
- SaltStack:Salt SSH
- 523. Continuous Subarray Sum
- 短线王的盯盘宝怎么样_2022考研英语韦林全程班怎么样?资源分享
- 三星10年旗舰彻底终结 5年前35次爆炸惊天下
- 数据结构-栈在括号匹配中的应用
- 使用Ingress来负载分发微服务
- 用android ndk编译ffmpeg,AndroidNDK交叉编译FFMPEG
- 项目分层思路——管家婆
- 为什么要使用向量化?
- 常用经典SQL语句大全完整版--详解+实例
- 不透明度十六进制_十六进制不透明度表
- groupby分组聚合和运算2
- 若依集成minio实现分布式文件存储
- error CS0234: 命名空间“XXX”中不存在类型或命名空间名“MVC”(是否缺少程序集引用?)
- 基于Opensips+Rtpengine+Freeswitch实现的网络电话系统
- 5个国内优秀网站设计案例分享
- java删除表格_Java 创建、删除Word表格
- Python:王老先生有块地