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="~/ ...
随机推荐
- POJ1753 搜索
Flip Game Description Flip game is played on a rectangular 4x4 field with two-sided pieces placed on ...
- Socket-IOS
Socke Socket又称"套接字” 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. 应用程序通常通过"套接字"向网络发出请 ...
- gulp实时编译less,压缩合并requirejs模块文件
gulp的使用命令简单,就几个,gulp的简单使用教材可以参考一点的gulp使用教材(http://www.ydcss.com/archives/18). 下面就简单的介绍这些命令如何互相配合的完成前 ...
- JavaScript刷新页面的方法(包括Frame框架的刷新方式)
JavaScript刷新页面的方法 1 history.go(0) 去指定的某页 2 window.location.reload()刷新当前页面 window.location.relo ...
- 数据库MySQL调优实战经验总结
MySQL 数据库的使用是非常的广泛,稳定性和安全性也非常好,经历了无数大小公司的验证.仅能够安装使用是远远不够的,MySQL 在使用中需要进行不断的调整参数或优化设置,才能够发挥 MySQL 的最大 ...
- React 笔记
跟我一起学 React
- AJSX 传输数组
如果要利用ajax传输数组,或者传输多个(不知道有多少个)class的某一属性的值,例如: 要将这三个数据传入php编辑界面,图片显示有三个数据,但实际上,数据的多少是由数据库所导出的数据 决定的.如 ...
- HNOI2015 Day 2题解
昨天做了HNOI day 2,感觉好像还是可做的,想当年什么splay还是高级算法,现在点剖什么就老考了简直丧病,虽然第二题还没写那就先当下嘴巴选手吧= = T1:[HNOI2015]落忆枫音 描述: ...
- [Selenium With C#学习笔记] Lesson-01环境搭建
Step-1:准备所需的开发环境.浏览器驱动.Selenium-Webdriver.单元测试框架,因目前使用C#的开发神器都Visual Studio,本文也打算采用Visual Studio 201 ...
- 教你如何一步步将项目部署到Github
注册Github账号有半年多的时间,却一直不知道如何将自己做好的项目部署到Github中.看了网上许多的教程,要么一开始就来Git命令行,要么直接就来一堆术语,很少能够真正说中要点,解决我们的烦恼. ...