MySQL+SSM+Ajax上传图片问题
第一次写上传图片的代码,碰到很多问题。昨天做了整整一天,终于在晚上的时候成功了。大声欢呼。
但是,做完之后,还是有很多问题想不通。所以在这里也算是写个笔记,日后忘记了可以回顾,也算请教各路朋友。(^_^)
Q.1. 网上说Ajax不能上传文件,但是这个说法并不是很多,也还是有蛮多通过Ajax上传文件的分享。
我也没有通过Ajax做出来,最后是通过AjaxSubmit这个方法写的。
Q.2. AjaxSubmit这个方法对文件上传的大小有默认限制吧。我选择大于100KB的文件上传就不能成功,小于100KB的就可以成功。
上传大于100KB的时候,浏览器console返回下面的提示。说明他还是执行了ajaxSubmit的success方法,并返回textStatus的值为success,
但是XMLHttpRequest, 和 errorThrown的responseText返回的HTML代码内容是我在spring-web.xml配置的异常处理视图网页。
js代码(提交表单事件):
function postImg(){
if ($.trim($("#imgFile").val()) == "") {
alert("请选择图片!");
return;
}
console.log($("#imgFile")[0].files[0].size);//小于100*1024,下面的请求就可以成功
var option = {
url : '/cloudnote/user/insertUserPhoto.do',
type : 'POST',
// dataType : 'json',
headers : {"ClientCallMode" : "ajax"}, //添加请求头部
success : function(XMLHttpRequest, textStatus, errorThrown){
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
console.log("前端输出上传成功");
$("#imgClose").click();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
console.log("前端输出上传失败");
}
};
$("#imgForm").ajaxSubmit(option);
return false; }
前端HTML表单:
<form id="imgForm" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">修改头像</h4>
</div>
<div class="modal-body">
<input type="file" id="imgFile" name="imgFile"/>
<input id="imgId" name="userId" value="${user.id }" style="display:none" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="imgClose">关闭</button>
<button type="button" class="btn btn-primary" onclick="postImg();" id="imgSubmit">上传</button>
</div>
</div>
</form>
下面是后台的java代码(Controller)
//更新用户头像
@RequestMapping(value="/insertUserPhoto.do",method = RequestMethod.POST)
public void insertUserPhoto(
HttpServletRequest req, HttpServletResponse res){ System.out.println("----- 插入图片 -------");
try{
String id = req.getParameter("userId");
System.out.println(id);
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req; MultipartFile file = multipartRequest.getFile("imgFile");
byte[] photo = file.getBytes();
boolean result = serv.insertUserPhoto(id, photo);
res.setContentType("text/html;charset=utf8");
res.getWriter().write("result:" + result); }catch(Exception e){
e.printStackTrace();
}
System.out.println("----- 插入图片end -------");
}
/**
* 读取用户头像
* @param req
* @param res
*/
@RequestMapping(value="/readPhoto.do", method=RequestMethod.GET)
public void readPhoto(HttpServletRequest req, HttpServletResponse res){
System.out.println("------readPohto-----");
String id = Utils.getSessionUserId(req); try {
User user = serv.selectUserPhoto(id); res.setContentType("image/jpeg");
res.setCharacterEncoding("utf-8"); OutputStream outputStream = res.getOutputStream();
InputStream in = new ByteArrayInputStream(user.getPhoto()); int len = 0;
byte[] buf = new byte[1024];
while((len = in.read(buf,0,1024)) != -1){
outputStream.write(buf, 0, len);
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("-----readPohto end-----");
return;
}
Service实现类
//查找用户图片(头像)
public User selectUserPhoto(String id) throws ImageException {
User user = userDao.findUserById(id);
if(user == null){
throw new UserNameException("用户名不存在!");
} Map<String, Object> data = userDao.selectUserPhoto(id);
System.out.println(data);
user.setPhoto((byte[]) data.get("photo")); return user;
}
//更新用户图片(头像)
public boolean insertUserPhoto(String userId, byte[] photo) throws ImageException, UserNameException {
if(userId == null || userId.trim().isEmpty()){
throw new UserNameException("用户id不存在");
} User user = userDao.findUserById(userId);
if(user == null){
throw new UserNameException("用户不存在");
} user.setPhoto(photo);
int n = userDao.updateUserPhoto(user);
System.out.println("插入图片:" + n);
return n==1?true:false;
}
实体类User的photo 是 byte[] 类型的;
数据库的photo是 longblob:
mapper映射器:
<!-- 更新图片 -->
<update id="updateUserPhoto" parameterType="cn.tedu.note.entity.User">
UPDATE user set id = #{id}, photo = #{photo,jdbcType=BLOB} <!-- 这里试了,如果不加jdbcType=BLOB 会出错,虽然不是很理解,但也照做了 -->
WHERE id = #{id}
</update>
<!-- 获取图片 -->
<select id="selectUserPhoto" parameterType="String" resultType="Map">
SELECT id as id, photo as photo from user
WHERE id=#{id}
</select>
Spring-web.xml配置
<!-- 文件上传表单的视图解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize"><value>100000</value></property>
<property name="defaultEncoding"><value>UTF-8</value></property>
</bean>
MySQL+SSM+Ajax上传图片问题的更多相关文章
- ajaxfileUpload ajax 上传图片使用
前台html: <div class="b-mg15 img-text" room_id="<?= $items['id'] ?>"> ...
- ajax上传图片
选择文件后 ajax上传图片到后台,后台执行保存操作,返回上传的图片路径,显示到页面 需要引入ajaxfileupload.js js代码 <script type="text/jav ...
- 使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器
使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器 ajax上传主要使用了 var reader = new FileReader() 此方法 js图片压缩主要是利用canvas进 ...
- Ajax上传图片以及上传之前先预览
手头上有几个小项目用到了easyUI,一开始决定使用easyUI就注定了项目整体上前后端分离,基本上所有的请求都采用Ajax来完成.在文件上传的时候用到了Ajax上传文件,以及图片在上传之前的预览效果 ...
- asp.net core 通过ajax上传图片及wangEditor图片上传
asp.net core 通过ajax上传图片 .net core前端代码,因为是通过ajax调用,首先要保证ajax能调用后台代码,具体参见上一篇.net core 使用ajax调用后台代码. 前端 ...
- vuejs使用FormData对象,ajax上传图片文件
我相信很多使用vuejs的朋友,都有采用ajax上传图片的需求,因为前后端分离后,我们希望都能用ajax来解决数据问题,传统的表单提交会导致提交成功后页面跳转,而使用ajax能够无刷新上传图片等文件. ...
- php form表单ajax上传图片方法
form表单ajax上传图片方法 先引用jquery.form.js 前台代码<pre><form id="form1"> <input id=&qu ...
- 使用ajax上传图片,并且使用canvas实现出上传进度效果
前端代码: <%@ page contentType="text/html;charset=UTF-8" language="java" %> &l ...
- 十六、ajax上传图片 mvc
一.ajax上传图片 mvc 前台html <img id="uploadimg1" class="uploadimg" src="~/ ...
随机推荐
- es6笔记3^_^object
一.destructuring ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构Destructuring. //es5 if(1){ let cat = 'ken'; le ...
- Ionic在windows下的环境配置难题
具体的配置方法网上有很多,可以参考http://my.oschina.net/JeeChou/blog/219699?fromerr=k1hPtBUs,但问题还是会有,我总结的主要有以下几个方面: 1 ...
- Windows下Python读取GRIB数据
之前写了一篇<基于Python的GRIB数据可视化>的文章,好多博友在评论里问我Windows系统下如何读取GRIB数据,在这里我做一下说明. 一.在Windows下Python为什么无法 ...
- win10环境下python3.5安装步骤
点我去Python官网下载 往下翻几页就能看到各种版本的Python,当前最新的是Python3.6,也没多大区别,我选择的是3.5.2 64位的,点击download 根据自己的电脑配置,我选择的是 ...
- Unity随手记
过年11天假期,带娃带了7天,吃吃喝喝.也看了点书,<射雕英雄传>(书)看了一半,还有就是在看<unity官方案例精讲>这本. 随手记一些自觉有价值或者有意思的点. 1. 对脚 ...
- [2017.02.07] Lua入门学习记录
#!/home/auss/Projects/Qt/annotated/lua -- 这是第一次系统学习Lua语言 --[[ 参考资料: 1. [Lua简明教程](http://coolshell.cn ...
- asp.net权限认证:OWIN实现OAuth 2.0 之密码模式(Resource Owner Password Credential)
asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...
- GIS制图课程目录
由于更新次序跳跃式更新,因此很有必要整理一下全书目录,并将会按照实际学习的顺序进行更新. [前言] GIS制图课程前言 [理论篇] 理论篇-地图学与GIS制图的基础理论(一) 理论篇-地图学与GIS制 ...
- iOS 即时通讯 + 仿微信聊天框架 + 源码
这些你造吗? 即时通讯(IM),在IOS这片江湖里面已经算是一个老者了,我这小旋风也是在很早以前巡山的时候,就知道有即时通讯这个妖怪,以前也多多少少接触过一些,在造APP的时候用过,哎呀,说着说着就感 ...
- Ionic 2 中创建一个照片倾斜浏览组件
内容简介 今天介绍一个新的UI元素,就是当我们改变设备的方向时,我们可以看到照片的不同部分,有一种身临其境的感觉,类似于360全景视图在移动设备上的应用. 倾斜照片浏览 Ionic 2 实例开发 新增 ...