Java method for uploading files to the server.

Source: Internet
Author: User

Java method for uploading files to the server.

Web file upload adopts the POST method. Unlike the POST submission FORM, the enctype attribute of form must be set to multipart/FORM-data for file upload. because the uploaded file is large, you need to set this parameter to specify that the browser uses binary upload. If this parameter is not set, the default enctype attribute is application/x-www-form-urlencoded. the browser uses ASCII to send data to the server, leading to File Sending failure.

To upload a file, use the file field (<input type = 'file'/>, and set the Enctype of FORM to multipart/form-data.

Client upload page:

CodeAs follows:

Upload.html

<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

The code running on the client is simple, and the server must be more complex. To obtain the content, you must parse the Request submitted by the browser according to the format specified by the HTTP protocol.

It is troublesome to parse binary streams. Many class libraries have completed this task, such as SmartUpload and Apache Commons Fileupload. smartUpload is a commercial library that stores data in the memory during Request Parsing. Therefore, it is fast, but memory overflow occurs when a large file is uploaded. Apache Commons Fileupload is a free open-source class library. Some frameworks, such as Struts, integrate the Apache Common Fileupload class library to upload files.

:

The Code is as follows:

Package com. helloweenvsfei. servlet; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import java. io. printWriter; import java.net. URLEncoder; import java. util. list; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServl EtResponse; import org. apache. commons. fileupload. diskFileUpload; import org. apache. commons. fileupload. fileItem; import org. apache. commons. fileupload. fileUploadException; public class UploadServlet extends HttpServlet {private static final long serialVersionUID = response; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {res Ponse. setCharacterEncoding ("UTF-8"); response. getWriter (). println ("upload files in POST mode") ;}@ SuppressWarnings ("unchecked") public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {File file1 = null, file2 = null; String description1 = null, description2 = null; response. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html"); PrintW Riter out = response. getWriter (); out. println ("<! Doctype html public \ "-// W3C // dtd html 4.01 Transitional // EN \"> "); out. println ("<HTML>"); out. println ("<HEAD> <TITLE> A Servlet </TITLE> </HEAD>"); out. println ("<link rel = 'stylesheet 'type = 'text/css 'href = '.. /css/style.css '> "); out. println ("<BODY>"); out. println ("<div align = center> <br/>"); out. println ("<fieldset style = 'width: 90% '> <legend> Upload File </legend> <br/>"); out. println ("<div class = 'line'>"); out. Println ("<div align = 'left' class = 'leftdiv '> upload log: </div>"); out. println ("<div align = 'left' class = 'rightdiv '>"); // use the DiskFileUpload object to parse request DiskFileUpload diskFileUpload = new DiskFileUpload (); try {// place the parsed result in List <FileItem> List = diskFileUpload. parseRequest (request); out. println ("traverse all FileItem... <br/> "); // traverses all fileitems in the list for (FileItem: list) {if (fileItem. isF OrmField () {// if it is a text field if ("description1 ". equals (fileItem. getFieldName () {// If the FileItem name is description1 out. println ("traverse to description1... <br/> "); description1 = new String (fileItem. getString (). getBytes (), "UTF-8");} if ("description2 ". equals (fileItem. getFieldName () {// If the FileItem name is description2 out. println ("traverse to description2... <br/> "); description2 = new String (fileItem. getString (). ge TBytes (), "UTF-8") ;}} else {// otherwise, for the file domain if ("file1 ". equals (fileItem. getFieldName () {// File object created in the client File path File remoteFile = new File (new String (fileItem. getName (). getBytes (), "UTF-8"); out. println ("traverse to file1... <br/> "); out. println ("client file location:" + remoteFile. getAbsolutePath () + "<br/>"); // put the Server File In the upload folder file1 = new File (this. getServletContext (). getRealPath ("attachment"), remoteFile. getN Ame (); file1.getParentFile (). mkdirs (); file1.createNewFile (); // write the content of the FileItem file to InputStream ins = fileItem. getInputStream (); OutputStream ous = new FileOutputStream (file1); try {byte [] buffer = new byte [1024]; int len = 0; while (len = ins. read (buffer)>-1) ous. write (buffer, 0, len); out. println ("saved files" + file1.getAbsolutePath () + "<br/>");} finally {ous. close (); ins. close () ;}} if ("f Ile2 ". equals (fileItem. getFieldName () {// File object created in the client File path File remoteFile = new File (new String (fileItem. getName (). getBytes (), "UTF-8"); out. println ("traverse to file2... <br/> "); out. println ("client file location:" + remoteFile. getAbsolutePath () + "<br/>"); // put the Server File In the upload folder file2 = new File (this. getServletContext (). getRealPath ("attachment"), remoteFile. getName (); file2.getParentFile (). mkdirs (); file2. CreateNewFile (); // write the file and write the file content of FileItem to the file. InputStream ins = fileItem. getInputStream (); OutputStream ous = new FileOutputStream (file2); try {byte [] buffer = new byte [1024]; int len = 0; while (len = ins. read (buffer)>-1) ous. write (buffer, 0, len); out. println ("saved files" + file2.getAbsolutePath () + "<br/>");} finally {ous. close (); ins. close () ;}}} out. println ("Request parsed");} catch (FileUploa DException e) {// TODO Auto-generated catch block e. printStackTrace ();} out. println ("</div>"); out. println ("</div>"); if (file1! = Null) {out. println ("<div class = 'line'>"); out. println ("<div align = 'left' class = 'leftdiv '> file1: </div>"); out. println ("<div align = 'left' class = 'rightdiv '>"); out. println ("<a href = '" + request. getContextPath () + "/attachment/" + file1.getName () + "'target = _ blank>" + file1.getName () + "</a>"); out. println ("</div>"); out. println ("</div>");} if (file2! = Null) {out. println ("<div class = 'line'>"); out. println ("<div align = 'left' class = 'leftdiv '> file2: </div>"); out. println ("<div align = 'left' class = 'rightdiv '>"); out. println ("<a href = '" + request. getContextPath () + "/attachment/" + URLEncoder. encode (file2.getName (), "UTF-8") + "'target = _ blank>" + file2.getName () + "</a>"); out. println ("</div>"); out. println ("</div>");} out. println ("<div class = 'line'>"); out. println ("<div align = 'left' class = 'leftdiv '> description1: </div>"); out. println ("<div align = 'left' class = 'rightdiv '>"); out. println (description1); out. println ("</div>"); out. println ("</div>"); out. println ("<div class = 'line'>"); out. println ("<div align = 'left' class = 'leftdiv '> description2: </div>"); out. println ("<div align = 'left' class = 'rightdiv '>"); out. println (description2); out. println ("</div>"); out. println ("</div>"); out. println ("</fieldset> </div>"); out. println ("</BODY>"); out. println ("</HTML>"); out. flush (); out. close ();}}

Program running effect:

This article has been compiled into Java upload operation tips summary. You are welcome to learn and read this article.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.