1, because the upload file will be used to the Multiparthttpservletrequest object, we need to configure a parser in the SPRINGMVC configuration file
<!--in order to use the Multiparthttpservletrequest object that spring provides us with, we need to configure a parser-- <!--and for the bean component to work, You must configure an ID property-- <bean id= "Multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver "> <!--request Encoding-- < Property Name= "Defaultencoding" value= "UTF-8"/> <!--upload file size-- <property name= "Maxuploadsize" Value= "10000000"/> <!--buffer Size-- <property name= "maxinmemorysize" value= "1024x768"/> </ Bean>
2. Front-end JSP code
<div> <span> Upload attachments: </span><input type= "file" id= "Accessory1" name= "Accessory1" Onchange= "Checkfile (This)"/> <font size= "2" color= "Red" > Note: Upload file size cannot exceed 10m</font>
</div>
Upload file Check function checkfile (file) {var flag = GetFileSize (file); if (!flag) {var fileInput = $ ("#accessory1");
Validation does not pass, empty input box Fileinput.replacewith (Fileinput.clone ()); }} var fileSize = 0; The file size defaults to 0 function getfilesize (file) {/* (1) to determine the file suffix type */var STRs = new Array ();//define an array var Pic1 = $ (file). val (); Gets the value of the input box, file path STRs = Pic1.split ('. '); Divide into arrays storage var suffix = strs[strs.length-1]; Get file suffix if (suffix! = ' pdf ' && suffix! = ' docx ' && suffix! = ' doc ' && suffix! = ' tx T ') {alert ("can only upload files with the extension PDF, docx, doc, Text!) "); return false; }/* (2) Gets the file size in kilobytes */fileSize = file.files[0].size/1024; if (FileSize > 10000) {alert ("The file you selected is too large, select a file less than 10M!") "); return false; } return true; }
The method that is executed when the form is submitted var form = new FormData (); Form.append ("Accessory1", $ (' #accessory1 ') [0].files[0]);
Back-end request processing
@RequestMapping (value= "/addgg", Method=requestmethod.post) @ResponseBody public boolean ADDGG ( Multipartfile accessory1) {//Post an announcement if there is an attachment upload if (accessory1! = null) {
Logger.info ("<--with attachment announcement start-up"); InputStream is = null; try {is = Accessory1.getinputstream (); Byte[] B = new byte[is.available ()]; Is.read (b); Jjkjgggl.setacccontent (b); } catch (IOException e) { logger.info ("<--attachment read exception!) -->: "+e); throw new RuntimeException ("attachment Read exception! "); } finally{ try { is.close (); } catch (IOException e) { logger.info ("<--attachment read Release resource exception! -->: "+e); throw new RuntimeException ("attachment read frees resource exception! "); } } } return false; }
Attachment upload in Java