1,spring configuration file Add File upload configuration
<!--upload Files--<bean id="Multipartresolver" class="Org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--1GB-<property name="maxuploadsize"Value="1073741824"/> <property name="defaultencoding"Value="Utf-8"/> </bean>
2,html
<form method="Post"accept-charset="UTF-8"th:action="${#httpServletRequest. contextpath+ '/upload '}"Id="Multipartform"Enctype="Multipart/form-data" class="Form-search"role="form"> <input type="file"Name="file"Size="5"Id="file"/><button type="Submit"Id="multipart" class="btn"> Uploads </button> </form>
3,controller
1@RequestMapping (value ="/upload", method=requestmethod.post)2 @ResponseBody3 PublicString Upload (httpservletrequest request,httpservletresponse response, @RequestParam ("file") multipartfile file) {4 if(File.isempty ()) {5 returnResponsejson.instance (). SetStatus (false). Addalertmessage ("Please select import file! "). ToJSON ();6 }7String filename =file.getoriginalfilename ();8 intindex = Filename.indexof (".");9String File_suffix =filename.substring (Index, Filename.length ());Ten if(!file_suffix.equals (". txt")) { One returnResponsejson.instance (). SetStatus (false). Addalertmessage ("Please select TXT format file! "). ToJSON (); A } - Try { -BufferedReader reader =NULL; theString usernamestring =NULL; -InputStreamReader ISR =NULL; - intline =1; - Try { +ISR =NewInputStreamReader (File.getinputstream (),"Utf-8");//considering the encoding format -Reader =NewBufferedReader (ISR); + while((usernamestring = Reader.readline ())! =NULL) { ASystem. out. println (usernamestring); atline++; - } - -}Catch(FileNotFoundException e) { - //TODO auto-generated Catch block -Logger.error ("failed to read file! ", e); in}Catch(IOException e) { - //TODO auto-generated Catch block toLogger.error ("failed to read file! ", e); +}finally { - reader.close (); the isr.close (); * inch. Close (); $ }Panax Notoginseng}Catch(IOException e) { - //TODO auto-generated Catch block theLogger.error ("failed to upload file", e); + returnResponsejson.instance (). SetStatus (false). Addalertmessage ("failed to upload file"). ToJSON (); A } the returnResponsejson.instance (). SetStatus (true). ToJSON (); + } - $ /** $ * Written in TXT file format - * - * @param path the * @throws IOException - */Wuyi@RequestMapping (value ="/load") the Public voidWritetxt (httpservletrequest request, httpservletresponse response) throws IOException { -Response.setcontenttype ("Text/plain"); WuResponse.setcharacterencoding ("UTF-8"); -Response.setheader ("content-disposition","Attachment;filename=result.txt"); AboutString name_ip ="This is a TXT file"; $OutputStream Ops =NULL; - Try { -OPS =Response.getoutputstream (); - Ops.write (Name_ip.getbytes ()); A +}Catch(IOException e) { the //TODO auto-generated Catch block -Logger.error ("Write result file exception:", e); $}finally { the ops.close (); the } the the}
Spring uploads the download file