Commons fileupload implementation of File upload instance code _java

Source: Internet
Author: User
Tags file upload uuid

First, the principle of File upload analysis

    1, file upload the necessary prerequisite

A, form's method must be post

B, the Enctype property of the form must be of type Multipart/form-data.

Enctype Default value: application/x-www-form-urlencoded

Function: Inform the server of the MIME type of the request body

Application/x-www-form-urlencoded:username=abc&password=123

Servletrequest.getparameter (String name), which is a method that reads the type specifically

Multipart/form-data:

   2, the use of Commons-fileupload components to achieve file upload

A, copy jar package: Commons-fileupload.jar Commons-io.jar

b, the principle of implementation

    3, garbled problem

A, the normal field of garbled

Fileitem.getstring (String CharSet), encoding to be consistent with client

B, the uploaded Chinese file name garbled

Request.setcharacterencoding ("UTF-8"), encoding to be consistent with the client

    4, Concrete realization

Front upload.jsp code is as follows

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
 
 

Background servlet Code

Package com.itheima.servlet;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.io.UnsupportedEncodingException;
Import java.util.List;
Import Java.util.UUID;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.fileupload.FileItem;
Import Org.apache.commons.fileupload.FileUploadBase;
Import org.apache.commons.fileupload.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;
Import Org.apache.commons.io.FilenameUtils; Detailed public class UploadServlet3 extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse R Esponse) throws Servletexception, IOException {request.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text
/html;charset=utf-8 ");
PrintWriter out = Response.getwriter (); SYstem.out.print (Request.getremoteaddr ());
Boolean ismultipart = servletfileupload.ismultipartcontent (request);
if (!ismultipart) {throw new RuntimeException ("Please check the Enctype property of your form, OK is Multipart/form-data");}
Diskfileitemfactory dfif = new Diskfileitemfactory ();
Servletfileupload parser = new Servletfileupload (DFIF); Parser.setfilesizemax (3*1024*1024)//Set the size of a single file upload//Parser.setsizemax (6*1024*1024);//multiple file upload total size limit list<
fileitem> items = null; try {items = parser.parserequest (request);} catch (Fileuploadbase.filesizelimitexceededexception e) {out.write ("Upload file exceeds 3M"); catch (Fileuploadbase.sizelimitexceededexception e) {out.write ("Total file exceeds 6M"); catch (Fileuploadexception e) {e.printstacktrace (); throw new RuntimeException ("Parse upload failed, try again");}//Process request content if (items! =null) {for (Fileitem item:items) {if (Item.isformfield ()) {Processformfield (item);}
else{Processuploadfield (item);} } out.write ("Upload success!")
");
} private void Processuploadfield (Fileitem item) {try {String fileName = Item.getname (); User does not choose to upload file if (filename!=null&&!filename.equals ("")) {fileName = Uuid.randomuuid (). toString () + "_" +
Filenameutils.getname (FileName);
Extension String extension = filenameutils.getextension (fileName);
MIME type String contentType = Item.getcontenttype (); if (Contenttype.startswith ("image/")) {///Sub-directory Store: Date Resolution/now = new Date ();//DateFormat df = new SimpleDateFormat ("yyyy
-mm-dd ");
String childdirectory = Df.format (now); Calculates the storage directory String childdirectory = Makechilddirectory (Getservletcontext () by hashcode the file name. Getrealpath ("/web-inf/files/
"), fileName);
String Storedirectorypath = Getservletcontext (). Getrealpath ("/web-inf/files/" +childdirectory);
File Storedirectory = new file (Storedirectorypath);
if (!storedirectory.exists ()) {storedirectory.mkdirs ();}
System.out.println (FileName); Item.write (new file (Storedirectorypath+file.separator+filename));//delete temporary file}} catch (Exception e) {throw new Runtimeex
Ception ("Upload failed, please try again"); Compute the stored subdirectory private String MakechilddiRectory (String Realpath, String fileName) {int hashcode = Filename.hashcode (); int dir1 = hashcode&0xf;//take 1~4 bit int d
Ir2 = (hashcode&0xf0) >>4;//fetch 5~8 bit String directory = "" +DIR1+FILE.SEPARATOR+DIR2;
File File = new file (realpath,directory);
if (!file.exists ()) file.mkdirs ();
return directory; private void Processformfield (Fileitem item) {String fieldName = Item.getfieldname ();//field name string Fieldvalue; try {fie
Ldvalue = item.getstring ("UTF-8");
catch (Unsupportedencodingexception e) {throw new RuntimeException ("Do not support UTF-8 encoding");
System.out.println (fieldname+ "=" +fieldvalue); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {DoG
ET (request, response); }
}

5. On the issue of temporary documents

A, diskfileitemfactory

public void Setrepository (file repository): Setting up a storage directory for temporary files
public void Setsizethreshold (int sizethreshold): Setting the size of the cache

B

File upload, you use IO flow processing, be sure to delete the temporary file after the stream closes. Fileitem.delete ()

Recommended use: Fileitem.writer (file f). Temporary files are automatically deleted.

6, limit the size of the file

A

Servletfileupload.setfilesizemax (3*1024*1024);/Set the size of an individual file upload

B

Servletfileupload.setsizemax (6*1024*1024);//multiple file upload Total size limit

The above is a small set to introduce the Commons FileUpload implementation of File upload instance code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.