MySQL+SSM+Ajax上傳圖片問題的分析(圖)

黄舟
發布: 2018-05-11 15:14:11
原創
2867 人瀏覽過

本文主要介紹了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配置的異常處理視圖網頁。

MySQL+SSM+Ajax上傳圖片問題的分析(圖)

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" > 
  <p class="modal-content">
   <p class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
   <h4 class="modal-title" id="myModalLabel">修改头像</h4>
  </p>
  <p class="modal-body">
    <input type="file" id="imgFile" name="imgFile"/> 
   <input id="imgId" name="userId" value="${user.id }" style="display:none" />
  </p>
  <p 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>
  </p>
 </p>
</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:

MySQL+SSM+Ajax上傳圖片問題的分析(圖)

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上傳圖片問題的分析(圖)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!