SpringMVC + Ajax implements the object batch upload and download function instance code, springmvcajax

Source: Internet
Author: User
Tags temporary file storage

SpringMVC + Ajax implements the object batch upload and download function instance code, springmvcajax

Today, we have uploaded and downloaded files. To sum up, the basic web project establishment and SpringMVC framework establishment are not detailed here.

Upload form:

<Form id = "uploadfiles" enctype = "multipart/form-data"> <input type = "file" multiple = "multiple" id = "file_upload" name = "file_upload "/> <input type = "button" value = "upload" onclick = "upload () "/> </form>

Upload Ajax:

<Script type = "text/javascript">/** upload File */function upload () {var formData = new FormData ($ ("# uploadfiles") [0]); $. ajax ({type: "post", url :". /path/upload ", dataType:" json ", data: formData,/*** must be false to automatically add the correct Content-Type */contentType: false, /*** it must be false to avoid jQuery's default formdata Processing * XMLHttpRequest will correctly process formdata */processData: false, success: function (data) {// process the data returned from the backend if (data) { Lert ("Upload successful! ");} Else {alert (" Upload Failed! ") ;}}, Error: function (err) {// submit error $ (" # msg ").html (JSON. stringify (err); // output the response information alert ("no response from the server") ;}}</script>

Spring. xml configuration:

<! -- Configuration File Upload --> <bean id = "multipartResolver" class = "org. springframework. web. multipart. commons. CommonsMultipartResolver"> <! -- Default encoding --> <property name = "defaultEncoding" value = "UTF-8"/> <! -- Maximum file size --> <property name = "maxUploadSize" value = "10485760000"/> <! -- Maximum value in memory --> <property name = "maxInMemorySize" value = "40960"/> </bean> controller: /** upload multiple files */@ RequestMapping (value = "/upload", produces = "application/json; charset = UTF-8 ") public @ ResponseBody boolean uploadFiles (@ RequestParam ("file_upload") MultipartFile [] files) {boolean result = false; String realPath; for (int I = 0; I <files. length; I ++) {if (! Files [I]. isEmpty () {String uniqueName = files [I]. getOriginalFilename (); // get the File name realPath = "E:" + File. separator + uniqueName; // The File Upload path. Here, the file is "files" [I]. transferTo (new File (realPath); // transfer object result = true;} catch (Exception e) {e. printStackTrace () ;}} return result ;}

The downloaded jsp page code is designed based on different requirements. The controller code is provided here:

/** Download multiple files */@ RequestMapping (value = "/download") public void downloadFiles (HttpServletResponse response) {String str = request. getParameter ("rows"); // download the file information, including the file name, storage path, and other JSONArray path = (JSONArray) JSONArray. parse (request. getParameter ("rows"); Path paths [] = new Path [path. size ()]; paths = JSONArray. parseArray (str, Path. class ). toArray (paths); String uri = "d:" + File. separator + "mldn.zip"; // temporary file storage path File zipFile = new File (uri); // defines the compressed File name ZipOutputStream zipOut = null; // declares the compressed stream object InputStream input = null; // Add the file to be compressed to the compressed output stream. try {zipOut = new ZipOutputStream (new FileOutputStream (zipFile);} catch (FileNotFoundException e) {e. printStackTrace () ;}for (int I = 0; I <paths. length; I ++) {File file = new File (paths [I]. getUri () + File. separator + paths [I]. getFilename (); try {input = new FileInputStr Eam (file); // defines the input stream zipOut of the file. putNextEntry (new ZipEntry (file. getName (); // set the ZipEntry object} catch (Exception e) {e. printStackTrace () ;}}// write the file to the compressed file int temp = 0; try {while (temp = input. read ())! =-1) {// read the zipOut content. write (temp); // write to the compressed file} catch (IOException e) {e. printStackTrace ();} finally {try {input. close (); zipOut. close ();} catch (IOException e) {e. printStackTrace () ;}try {// download an object in the form of a stream. BufferedInputStream FCM = new BufferedInputStream (new FileInputStream (zipFile); byte [] buffer = new byte [FCM. available ()]; FCM. read (buffer); FCM. close (); // clear response. reset (); OutputStream toClient = new BufferedOutputStream (response. getOutputStream (); response. setContentType ("application/x-msdownload;"); response. setHeader ("Content-Disposition", "attachment; filename =" + zipFile. getName (); toClient. write (buffer); toClient. flush (); toClient. close (); zipFile. delete (); // delete the generated Server File} catch (IOException ex) {ex. printStackTrace ();}}

Compress multiple files into one compressed package and delete the generated temporary compressed files.

If you submit a request using Ajax on the download page, note that the ajax function returns only xml, text, json, html, and Other types without the "stream" type. Therefore, we need to implement ajax download, the corresponding ajax function cannot be used for file download. However, you can use js to generate a form, use this form to submit parameters, and return "stream" type data.

Example:

Function download () {var form = $ ("<form>"); // defines a form. attr ("style", "display: none"); form. attr ("target", ""); form. attr ("method", "post"); form. attr ("action ",". /path/download "); // request url var input1 = $ (" <input> "); input1.attr (" type "," hidden "); input1.attr (" name ", "rows"); // set the attribute name input1.attr ("value", "test"); // set the attribute value $ ("body "). append (form); // place the form in the web form. append (input1); form. submit (); // form submission}

Summary

The above is an example code of the SpringMVC + Ajax file bulk upload and download function introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

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.