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 ...
最新文章
- 左神算法:未排序正数数组中累加和为给定值的最长子数组长度(Java版)
- 揭秘 RocketMQ 新特性以及在金融场景下的实践
- 上项线体表位置_心理成熟的人都有哪些具体表现呢?
- 路由器距离向量算法计算举例_文本去重算法:Minhash/Simhash/Klongsent
- 基于MRG_MyISAM引擎的Mysql分表
- 数据库设计说明文档自动生成(支持Mysql、Oracle和Postgres)
- 【计算机网络】IP地址
- 入职美团定级P7,总结2022年最新最全180道高级岗面试题及答案
- 魔法表格(MagicTable)入门教程--CAD转Excel、CAD多个表格批量转Excel
- 06 ElasticSearch模板搜索
- 亲测有效sudo: /etc/sudoers is world writable sudo: no valid sudoers sources found, quitting sudo: una
- android自定义网络请求框架,安卓快速开发框架(十九)XBaseAndroid Http网络请求
- 在sweetalert弹出窗插件中加入html代码
- 怎么取消苹果订阅自动续费?教你一招,2分钟搞定!
- 【ChatGPT机器人】打造你的私人聊天助手
- 案例:FIFA2018球员数据分析
- 全文检索服务ElasticSearch
- 网络教育专科计算机考试试题电子科大,电子科技大学网络教育专科英语(理)入学考试模拟题及答案...
- QQ批量同意好友验证,自动放人,autojs引流脚本,爆粉脚本
- Pytorch Lightning框架:使用笔记【LightningModule、LightningDataModule、Trainer、ModelCheckpoint】