servlet+jsp implementation of File upload and download

Source: Internet
Author: User

java File upload and download
By the micro-meter unit su Set method = "POST"
enctype = "Multipart/form-data" property, which enables the data submitted by the form to be submitted in binary encoding, in the servlet that receives this request
With the binary stream to get the content, you can get the content of the uploaded file, so as to achieve file upload.
Form Enctype Properties
Application/x-www-form-urlencoded: This is the default encoding, which only handles Value property values in form fields. Using
This coded form will process the value of the form field as a URL encoding
Multipart/form-data: This encoded form processes the form data in a binary stream, which encodes the file domain
The contents of the specified file are also encapsulated in the request parameters
Text/plain: This approach is primarily useful for sending mail directly through forms
File download
The value of the Content-type header field needs to be set by the Httpservletresponse.setcontenttype method.
MIME types that the browser cannot use in some way or activate a program to process
The value of the content-disposition header needs to be set by the Httpservletresponse.setheader method
"Attachment;filename= file name";
Read the download file and call the Httpservletresponse.getoutputstream method to return the Servletoutputstream
object to write the contents of the attachment file to the client
File Upload Implementation steps
Get stream information from request, save to temp file
Get the uploaded file name from the temporary file and the location of the file content

According to the location of the file, read the contents of the upload file, save to Local

JSP page

<form action= "uploadservlet.do" method= "post" enctype= "Multipart/form-data" ><input id= "myfile" Name= " MyFile "type=" file "/> <input type=" Submit "value=" commit "/>${result}</form> Download: <a href=" Downloadservlet.do?filename=test1.txt ">test1.txt</a> ${errorresult}

Upload

public class Uploadservlet extends HttpServlet {public void doget (HttpServletRequest req, HttpServletResponse resp) Throws Servletexception, IOException {doPost (REQ,RESP);} public void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {// Get stream information from request InputStream Filesource = Req.getinputstream (); String tempfilename = "E:/tempfile";//tempfile points to temporary file Tempfile = new file (tempfilename);// The Outputstram file output stream points to this temporary file FileOutputStream outputstream = new FileOutputStream (tempfile); byte b[] = new Byte[1024];int n; while ((n = filesource.read (b))! =-1) {outputstream.write (b, 0, n);} Turn off the output stream, input stream Outputstream.close (), Filesource.close ();//Get the name of the uploaded file Randomaccessfile randomfile = new Randomaccessfile ( Tempfile, "R");//l = new String (l.getbytes ("8859_1"), "GBK"); String str2 = Randomfile.readline ();//Encoding conversion str2 = new String (str2.getbytes ("8859_1"), "Utf-8"); System.out.println (STR2); String str = Randomfile.readline (), str = new String (str.getbytes ("8859_1"), "Utf-8"); System. out.println (str); int beginindex = Str.lastindexof ("=") + 2;int EndIndex = Str.lastindexof ("\" "); String filename = str.substring (beginindex, EndIndex); SYSTEM.OUT.PRINTLN ("FileName:" + filename);//relocate file pointer to file header randomfile.seek (0); Long startposition = 0;int i = 1;//Get file contents Start position while ((n = randomfile.readbyte ())! =-1 && i <=4) {if (n = = ' \ n ') {startposition = Randomfile.getfilepointer ( ); i + +;}} StartPosition = Randomfile.getfilepointer () -1;//Gets the end position of the file content Randomfile.seek (Randomfile.length ()); Long endPosition = Randomfile.getfilepointer (); int j = 1;while (endposition >=0 && j<=2) {Endposition--;randomfile.seek ( Endposition); if (randomfile.readbyte () = = ' \ n ') {j + +;}} Endposition = endposition-1;//Setting the path//path of the Save upload file can be set by itself String Realpath = "E:\\myeclipse workplace\\css+js";//string Realpath = Getservletcontext (). Getrealpath ("/") + "images"; File FileUpload = new file (Realpath); System.out.println (Realpath); if (!fileupload.exists ()) {Fileupload.mkdir ();} File SaveFile = new file (realpath,fIlename); Randomaccessfile randomaccessfile = new Randomaccessfile (saveFile, "RW");//Read the contents of the file from the temporary file (obtained from the start and end location) Randomfile.seek ( StartPosition); while (StartPosition < endposition) {Randomaccessfile.write (Randomfile.readbyte ()); startPosition = Randomfile.getfilepointer ();} Close the input and output stream, delete temporary files randomaccessfile.close (); Randomfile.close (); Tempfile.delete (); Req.setattribute ("Result", "Upload succeeded!") "); RequestDispatcher dispatcher = Req.getrequestdispatcher ("test.jsp");d Ispatcher.forward (req, resp);}}

Download file

public class Downloadservlet extends HttpServlet {public void doget (HttpServletRequest req, HttpServletResponse resp) Throws Servletexception, IOException {//req.setcharacterencoding ("Utf-8");//resp.setcharacterencoding ("Utf-8");// Resp.setcontenttype ("Text/html;charset=utf-8");//req.setcharacterencoding ("Utf-8");//resp.setcontenttype ("Text /html;charset=utf-8 "),//Resp.setcontenttype (" Text/plain ");//encode the conversion because the Chinese resp.setheader is not recognized (" Content-type "," Text/html;charset=utf-8 "); String path = Getservletcontext (). Getrealpath ("/") + "images/"; String filename = req.getparameter ("FileName"); string filename = Null;filename = new String (Filename.getbytes ("8859_1"), "Utf-8"),//filename = new String ( Filename.getbytes ("8859_1"), "uft-8"); System.out.println ("Path:" + path + "FileName:" + filename); File File = new file (path + filename), if (File.exists ()) {//Because the browser does not recognize the encoding when the download is not in the same language as the browser, it is converted to string value = new String ( Filename.getbytes ("Utf-8"), "iso-8859-1"); Resp.setcontenttype ("Application/x-msdownload"); Resp.setHeader ("Content-disposition", "attachment;filename=\" "+ Value +" \ ""); InputStream InputStream = new FileInputStream ( file); Servletoutputstream outputstream = Resp.getoutputstream (); byte b[] = new Byte[1024];int N;while ((n = inputstream.read (b) )! =-1) {outputstream.write (b, 0, n);} Outputstream.close (); Inputstream.close ();} else {req.setattribute ("Errorresult", "file does not exist download failed!! "); Resp.sendredirect (" luntan.jsp ");}} public void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {doget (req, RESP);}}


servlet+jsp implementation of File upload and download

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.