File upload and download is often the problem of network programming, although relatively basic but often forget some details, so here will be some details po out.
1. File download
File download is simple, front-end we only need to make a GET request:
1 <Buttononclick= ' getFile (); '>Import</Button>2 3 <Script>4 functionGetFile () {5 varURL= "/istore/servlet/b2b/group/downloadmodel.do";6 window.location.href=URL; //write here to jump to the Sevlet7 }8 </Script>
View Code
Backstage Sevelet the content back to the foreground here I created an Excel file myself as output:
1 Public voidDownloadmodel (httpservletrequest request,2HttpServletResponse response)throwsIOException, Rowsexceededexception, writeexception {3 4String filename = "Model.xls";//saved default file name5 6Response.setheader ("Content-disposition", "Attachment;filename="7+ urlencoder.encode (filename, "UTF-8"));//set the file name to the returned header information (very important)8OutputStream out = Response.getoutputstream ();//set the returned data stream9Writableworkbook Workbook =Workbook.createworkbook (out);TenWritablesheet sheet = workbook.createsheet ("Inputlist", 0); OneLabel Lab =NULL; ALab =NewLabel (0, 0, "LogonId"); -Sheet.addcell (Lab);//to create an Excel procedure, use the Jexcel -Workbook.write ();//Write the workbook.close (); -}
View Code
2. File Upload
The front desk only writes the JS code (using the jquery syntax)
function Upload () {var file= $ ("#uploadfile") File.after (File.clone (). Val ("")); File.remove (); $("#groupId"). Val (xgroup_id); var URL= "/istore/servlet/b2b/group/bulkupload.do"; //determine if the file is emptyvar uploadfile = jQuery ("#uploadfile"). Val (); if(uploadfile== "") {alert ("Please select the file, want to upload!"); return; }//determine if the extension is correct if (Uploadfile.tolowercase (). IndexOf ('. xls ') ==-1) {Alert ("The file you choosed are not a valid File,please select the valid files (extension '. xls ')!"); return; }Else{ $( This). dialog ("Close" ); //Submit Requestvar options ={url: ' Bulkupload.do ', type: ' Post ', DataType: ' JSON ', Success:function (data) {alert (data); } }
Background servlet:
PublicString Upload_member (httpservletrequest request, httpservletresponse response, @RequestParam ( c6>"UploadFile") multipartfile file) {PrintWriter out=NULL;//encoded format for uploadingResponse.setcontenttype ("Text/html;charset=utf-8"); String result=NULL; Try {//print is an output function I wrote that outputs the contents of the stream, and UploadFile saves the content and returns the saved stateprint (File.getinputstream ()); Result=uploadfile (file, request); } Catch(Exception e) {}returnjsonobject.tojsonstring (Result); }
This does not specifically write out the output data stream and save the data stream to the file, the reader can find the solution according to their own situation.
Web File upload and download