All process of uploading images using Spring Mvc

Source: Internet
Author: User

I got it from google and Baidu and at for a long time ......, Hope to help you.

Let's look at the code ......

     Image:  
 Init: function (uuid) {// this. identifier is the set global variable, and uuid is the unique encoding during page loading this. identifier = uuid; // Image Upload var idf = this. identifier; var that = this; $ ('#' + idf + '-tform '). ajaxForm ({dataType: 'json', beforeSubmit: function (a, f, o) {comment ('{'{idf}'-statuspic'{.html ('uploading... ') ;}, success: function (data) {if (typeof (data) = 'string') data = eval (' + data + ')'); $ ('#' + idf + '-uploadwindow '). window ('close '); If ("success" = data. message) {$ ('div [identifier = '+ that. identifier + ']'). find ('# picpath '). val (data. path); $ ("#" + idf + "-path "). val (data. path); $ ("#" + idf + "-statusPic" preview .html ("preview");} else if ("error" = data. message) $ ("#" + idf + "-statusPic" ).html ("non-image data! "); Else $ (" # "+ idf +"-statusPic "..html (" An error occurred while uploading data! "); $ (" # "+ Idf +"-itemPic "). val ('');}, error: function (jqXHR, textStatus, errorThrown) {$ ('# $' + idf + '-uploadWindow '). window ('close'); // console. log ("error:" + data. responseText); // console. log ("status:" + textStatus); $ ("#" + idf + "-statusPic" ).html ("Upload Failed! "); $ (" # "+ Idf +"-itemPic "). val ('');}});}
/***Upload the specified Image** @ Param request * @ param response * @ param command * @ return * @ throws Exception */public ModelAndView uploadFile (HttpServletRequest request, HttpServletResponse response, SmartMenu command) throws Exception {PrintWriter writer = null; try {response. setContentType ("application/json; charset = GBK"); writer = response. getWriter (); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRe Quest) request; String source = request. getSession (). getServletContext (). getRealPath ("/"); // get 1st images (the uploaded file is obtained based on the foreground name) MultipartFile imgFile1 = multipartRequest. getFile ("itemPic"); // determines whether the image is uploaded repeatedly (if the image is already uploaded, the old image will be deleted) String sourceImg = request. getParameter ("path"); if (imgFile1.getContentType (). split ("/") [0]. equals ("image") {if (null! = SourceImg &&! "". Equals (sourceImg) {System. out. println ("old image path:" + sourceImg); File f = new File (source + sourceImg); if (f. isFile () {f. delete (); System. out. println ("deleted successfully");} elseSystem. out. println ("deletion failed! ");} String path = null; if (imgFile1! = Null & imgFile1.getSize ()> 0) {path = this. getSmartMenuService (). storeFile (request. getSession (), imgFile1);} writer. print ("{\" message \ ": \" success \ ", \" path \ ": \" "+ path. replace ("\", "\") + "\"} ");} elsewriter. print ("{\" message \ ": \" error \ "}");} catch (Exception e) {// TODO: handle exceptionwriter. print ("{\" message \ ": \" no \ "}");} writer. flush (); writer. close (); return null ;}@ Overridepublic String StoreFile (HttpSession session, MultipartFile file) throws Exception {// TODO Auto-generated method stubString fileType = file. getContentType (). split ("/") [1]; String path = session. getServletContext (). getRealPath ("/"); String separator = File. separator; String uuid = UUID. randomUUID (). toString (); FileOutputStream fos = null; String fileName = null; try {InputStream FS = file. getInputStream (); // convert the file to png File files = new File (path + "\ dishpic") in the directory with the same name; // you can determine whether a folder exists. if not, create a folder if (! Files. exists () {files. mkdir ();} if (file. getContentType (). split ("/") [0]. equals ("image") {if (path. endsWith (separator) fileName = path + "dishpic" + separator + uuid + ". png "; elsefileName = path + separator +" dishpic "+ separator + uuid + ". png "; fos = new FileOutputStream (fileName); ImageUtil. convertFormat (FCM, fos, fileType, "png", 0, 0); fos. flush (); fos. close () ;}} catch (Exception ex) {System. out. Println ("failed to retrieve the file, error message:" + ex. getMessage (); if (fos! = Null) fos. close (); throw ex;} return "dishpic" + separator + uuid + ". png ";}/***1. Convert the row format of an image
*2. Moderate image size Cropping**/Public class ImageUtil {/***** @ param infile input file * @ param outfile output file * @ param srcFormat source format * @ param destFormat output format * @ return *@ throws Exception */public static boolean convertFormat (InputStream infile, outputStream outfile, String srcFormat, String destFormat, int width, int height) throws Exception {boolean flag = false; BufferedImage src = ImageIO. read (infile); if (height> 0 & width> 0) {// Compress the origin image if width and height are non-zeroheight = src. getHeight ()> height? Height: src. getHeight (); width = src. getWidth ()> width? Width: src. getWidth (); Image image = src. getScaledInstance (width, height, Image. SCALE_DEFAULT); // This is the BufferedImage tag = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB); Graphics g = tag. getGraphics (); // you can draw and change the following image. drawImage (image, 0, 0, null); // draw the reduced graph g. dispose (); tag. flush (); flag = ImageIO. write (tag, destFormat, outfile); // output to the scaled file stream} else {flag = ImageIO. write (src, destFormat, outfile); // output the original resolution image} Logger. getLogger (ImageUtil. class ). info ("image converted successfully: from [" + srcFormat + "] to [" + destFormat + "]"); return flag ;}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.