Image uploading in MySQL + SSM + Ajax,
The first time I wrote the code for uploading images, I encountered many problems. I made a whole day yesterday and finally succeeded in the evening. Cheers.
However, there are still many problems that cannot be found. Therefore, you can take a note here. If you forget it, you can review it later,Ask your friends.. (^_^)
Q.1.It is said on the Internet that Ajax cannot upload files, but there are not many such statements, and there are still a lot of shares about uploading files through Ajax.
I did not use Ajax either. I finally wrote it using the AjaxSubmit method.
Q.2.The AjaxSubmit method has a default limit on the file upload size. If you select a file larger than kb, the upload will fail. If you select a file smaller than kb, the upload will succeed.
When uploading data larger than kb, the browser console returns the following prompt. It indicates that the success method of ajaxSubmit is executed, and the value of textStatus is success,
But the content of the HTML code returned by XMLHttpRequest, and errorThrown responseText is my Exception Handling view page configured in the spring-web.xml.
Js Code (submit a form event ):
1 function postImg () {2 if ($. trim ($ ("# imgFile"). val () = "") {3 alert ("select an image! "); 4 return; 5} 6 console. log ($ ("# imgFile") [0]. files [0]. size); // less than 100*1024, the following request can be successful 7 var option = {8 url: '/cloudnote/user/insertUserPhoto. do ', 9 type: 'post', 10 // dataType: 'json', 11 headers: {"ClientCallMode": "ajax"}, // Add the request header 12 success: function (XMLHttpRequest, textStatus, errorThrown) {13 console. log (XMLHttpRequest); 14 console. log (textStatus); 15 console. log (errorThrown); 16 console. log ("frontend output uploaded"); 17 $ ("# imgClose "). click (); 18}, 19 error: function (XMLHttpRequest, textStatus, errorThrown) {20 console. log (XMLHttpRequest); 21 console. log (textStatus); 22 console. log (errorThrown); 23 console. log ("frontend output Upload Failed"); 24} 25}; 26 $ ("# imgForm "). ajaxSubmit (option); 27 return false; 28 29 30}
Front-end HTML form:
1 <form id = "imgForm"> 2 <div class = "modal-content"> 3 <div class = "modal-header"> 4 <button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true"> × </button> 5
The following is the background java code (Controller)
1 // update the user profile picture 2 @ RequestMapping (value = "/insertUserPhoto. do ", method = RequestMethod. POST) 3 public void insertUserPhoto (4 HttpServletRequest req, HttpServletResponse res) {5 6 System. out. println ("----- insert image -------"); 7 try {8 String id = req. getParameter ("userId"); 9 System. out. println (id); 10 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req; 11 12 MultipartFile file = m UltipartRequest. getFile ("imgFile"); 13 byte [] photo = file. getBytes (); 14 boolean result = serv. insertUserPhoto (id, photo); 15 res. setContentType ("text/html; charset = utf8"); 16 res. getWriter (). write ("result:" + result); 17 18} catch (Exception e) {19 e. printStackTrace (); 20} 21 System. out. println ("----- insert image end -------"); 22} 23/** 24 * read user profile 25 * @ param req26 * @ param res27 */28 @ RequestMapping (value = "/ ReadPhoto. do ", method = RequestMethod. GET) 29 public void readPhoto (HttpServletRequest req, HttpServletResponse res) {30 System. out. println ("------ readPohto -----"); 31 String id = Utils. getSessionUserId (req); 32 33 try {34 User user = serv. selectUserPhoto (id); 35 36 res. setContentType ("image/jpeg"); 37 res. setCharacterEncoding ("UTF-8"); 38 39 OutputStream outputStream = res. getOutputStream (); 40 InputStre Am in = new ByteArrayInputStream (user. getPhoto (); 41 42 int len = 0; 43 byte [] buf = new byte [1024]; 44 while (len = in. read (buf ))! =-1) {45 outputStream. write (buf, 0, len); 46} 47 outputStream. close (); 48} catch (IOException e) {49 e. printStackTrace (); 50} 51 System. out. println ("----- readPohto end -----"); 52 return; 53}
Service implementation class
1 // search for the User image (profile picture) 2 public User selectUserPhoto (String id) throws ImageException {3 user User = userDao. findUserById (id); 4 if (user = null) {5 throw new UserNameException ("the user name does not exist! "); 6} 7 8 Map <String, Object> data = userDao. selectUserPhoto (id); 9 System. out. println (data); 10 user. setPhoto (byte []) data. get ("photo"); 11 12 return user; 13} 14 // update user image (profile picture) 15 public boolean insertUserPhoto (String userId, byte [] photo) throws ImageException, userNameException {16 if (userId = null | userId. trim (). isEmpty () {17 throw new UserNameException ("User ID does not exist"); 18} 19 20 user User = userDa O. findUserById (userId); 21 if (user = null) {22 throw new UserNameException ("user does not exist"); 23} 24 25 user. setPhoto (photo); 26 int n = userDao. updateUserPhoto (user); 27 System. out. println ("insert image:" + n); 28 return n = 1? True: false; 29}
The object class User's photo is of the byte [] type;
The database's photo is longblob:
Mapper Er:
1 <! -- Update image --> 2 <update id = "updateUserPhoto" parameterType = "cn. tedu. note. entity. user "> 3 UPDATE user set id =#{ id}, photo =#{ photo, jdbcType = BLOB} <! -- I tried it here. If jdbcType = BLOB is not added, an error will occur. Although it is not very understandable, but we also did --> 4 WHERE id =#{ id} 5 </update> 6 <! -- Get image --> 7 <select id = "selectUserPhoto" parameterType = "String" resultType = "Map"> 8 SELECT id as id, photo as photo from user 9 WHERE id =#{ id} 10 </select>
Spring-web.xml Configuration
1 <! -- View Parser for file upload form --> 2 <bean id = "multipartResolver" class = "org. springframework. web. multipart. commons. commonsMultipartResolver "> 3 <property name =" maxUploadSize "> <value> 100000 </value> </property> 4 <property name =" defaultEncoding "> <value> UTF-8 </value> </property> 5 </bean>