Java implementation File Upload

Source: Internet
Author: User
Tags log log uuid

Recently in doing a small system to play when involved in the file upload, so on the internet to find the Java upload file scheme, and finally determine the use of common-fileupload to achieve upload operations.

    • Requirements Description

User Add page has an "Upload" button, click on the button to pop up the upload interface, upload completed after the upload screen is closed.

    • Required JAR Packages

Commons.fileupload-1.2.0.jar, Commons.logging-1.1.1.jar, Commons.beanutils-1.8.0.jar, Commons.collections-3.2.0.jar, Commons.io-1.4.0.jar, Commons.lang-2.1.0.jar

    • Achieve results
/** * Jump to upload page * functionId: Feature ID * fileType: File type * maxSize: File capacity Limit * Callback: callback function, return three parameters: file real name, file name and file size */function Openuplo AD (functionid,filetype,maxsize,callback) {var url = root+ "/commoncontroller.jhtml?method=gofileupload&"; if ( functionid!=null) {url = url + "functionid=" +functionid+ "&";} if (filetype!=null) {url = url + "filetype=" +filetype+ "&";} if (maxsize!=null) {url = url + "maxsize=" +maxsize;} var win = window.showModalDialog (URL, "", "Dialogwidth:300px;dialogheight:150px;scroll:no;status:no"); if (win! = null) {var Arrwin = Win.split (","); callback (arrwin[0],arrwin[1],arrwin[2]);}}

User to add the page related code, click on the "Upload" button to invoke the above core JS code, and get the return value

<script>.......function Openupload_ () {openupload (null, ' jpg,gif,jpeg,png ', ' 5 ', callback);} /** * callback function, get upload file information * realname Real file name * savename File Save name * maxSize file Actual size */function callback (realname,savename,maxsize) {$ ("# Photo_ "). Val (savename);//callback after other operations}</script><tr><td> Avatar: </td><td><input type=" Hidden "name=" photo "id=" photo_ "></input><input type=" button "onclick=" Openupload_ () "value=" Upload "/> </td></tr>

File upload JSP code, it is necessary to note that the head tag is added <base target= "_self" > to prevent the page to jump when the new window, the user select the specified file, click on Upload to submit form access to the specified background code

<%@ include file= "/web-inf/jsp/header.jsp"%><%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

  

Commoncontroller currently has two methods, one is to jump to upload the page method, one is to perform the upload operation method Dofileupload, upload method run the approximate logic is: first get the page request parameters, filetype to limit the upload file format,

MaxSize is used to limit the maximum upload file, then create upload directory upload.

public class Commoncontroller extends Basecontroller {log log = Logfactory.getlog (Commoncontroller.class); Properties Fileuploadpro = Null;public Commoncontroller () {Fileuploadpro = Propertiesutil.getpropertiesbyclass (" Fileupload.properties ");} @Overridepublic modeandview Init (httpservletrequest request,httpservletresponse response) throws Servletexception, IOException {return null;} /** * Jump to File upload page * @param request * @param response * @return * @throws servletexception * @throws ioexception */public Mode Andview gofileupload (httpservletrequest request,httpservletresponse response) throws Servletexception, IOException { String functionId = Request.getparameter ("FunctionId"); String FileType = Request.getparameter ("FileType"); String maxSize = Request.getparameter ("MaxSize"); Modeandview Mav = new Modeandview ("/web-inf/jsp/common/fileupload.jsp"); if (Functionid!=null &&! "". Equals (Functionid.trim ())) {Mav.addobject ("functionId", FunctionId);} if (filetype!=null &&! "". Equals (FileType.Trim ())) {Mav.addobject ("FileType", FileType);} if (maxsize!=null &&! "". Equals (Maxsize.trim ())) {Mav.addobject ("maxSize", maxSize);} return MAV;} /** * Upload file * @param request * @param response * @return * @throws servletexception * @throws ioexception * * @SuppressWarnin GS ("unchecked") public Modeandview dofileupload (httpservletrequest request,httpservletresponse response) throws Servletexception, IOException {//Gets and resolves the file type and supports a maximum value of string functionId = Request.getparameter ("FunctionId"); String FileType = Request.getparameter ("FileType"); String maxSize = Request.getparameter ("maxSize");//Temp directory name string temppath = Fileuploadpro.getproperty ("TempPath");// Real directory name String filePath = Fileuploadpro.getproperty ("FilePath"); Fileutil.createfolder (TempPath); Fileutil.createfolder (FilePath);D iskfileitemfactory factory = new Diskfileitemfactory ();// Maximum cache Factory.setsizethreshold (5*1024);//Set Temporary file directory factory.setrepository (new file (TempPath)); Servletfileupload upload = new Servletfileupload (factory); if (Maxsize!=null &&! "". Equals (Maxsize.trim ())) {//File Max maximum Upload.setsizemax (integer.valueof (maxSize) *1024*1024);} try {//Get all Files list list<fileitem> items = upload.parserequest (request); for (Fileitem Item:items) {if (! Item.isformfield ()) {///filename string filename = Item.getname ();//Check file suffix format string fileend = Filename.substring ( Filename.lastindexof (".") +1). toLowerCase (); if (Filetype!=null &&! "". Equals (Filetype.trim ())) {Boolean isrealtype = false; string[] Arrtype = Filetype.split (","); for (String Str:arrtype) {if (Fileend.equals (Str.tolowercase ())) {Isrealtype = True;break;}} if (!isrealtype) {//Prompt error message: File format is incorrect super.printjsmsgback (response, "file format is incorrect!"); return null;}} Create file unique name string uuid = Uuid.randomuuid (). toString ();//True upload path stringbuffer sbrealpath = new StringBuffer (); Sbrealpath.append (FilePath). Append (UUID). Append ("."). Append (fileend);//write file filename = new file (sbrealpath.tostring ()); Item.write (file);//upload successful, return data to the parent form: Real file name, virtual file name, File size StringBuffer sb = new StringBuffer (); Sb.append ("Window.returnvalue="). Append (FileName). Append (","). Append (UUID). Append ("."). Append (Fileend). Append (","). Append (File.length ()). Append ("';"); Sb.append ("Window.close ();"); Super.printjsmsg (response, sb.tostring ()); Log.info ("Upload file succeeded, JS message:" +sb.tostring ());} End of If}//end of For}catch (Exception e) {//Hint error: such as file size Super.printjsmsgback (response, "Upload failed, file size cannot exceed" +maxsize+ "m!"); Log.error ("Upload file Exception!", e); return null;} return null;}}

At this point a file upload has been implemented, and can basically meet the different modules of the upload commonality, I also have a functionid parameter for different modules to upload files to different directories.

------------------------------------------Another way--------------------------------------

1,jsp page

    <center>        

To implement a file upload, the form tag must contain enctype= "Multipart/form-data" (RFC1867 Protocol: http://www.faqs.org/rfcs/rfc1867.html) and must be POST mode upload.

2,web.xml Configuration

    <servlet>        <servlet-name>AddDataServlet</servlet-name>        <servlet-class>kxjh. adddataservlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name> adddataservlet</servlet-name>        <url-pattern>/adddata</url-pattern>    </ Servlet-mapping>

3,servelt implementation (commons-fileupload-1.2.1, commons-io-1.4)

        Parse request to determine if there is an upload file, Boolean ismultipart = servletfileupload.ismultipartcontent (request); if (Ismultipart) {//Create disk factory, use constructor to implement memory data storage and temporary storage path diskfileitemfactory factory = new DISKFILEITEMFA            Ctory (1024x768 * 4, New File ("D:\\temp"));            Set up to allow only data stored in memory, in bytes//factory.setsizethreshold (4096);            Set file temporary storage path//factory.setrepository (New file ("D:\\temp"));             Generate a new file upload handler servletfileupload upload = Servletfileupload (factory);            Set the path, file name of the character set upload.setheaderencoding ("UTF-8");            Set allow user to upload file size in bytes Upload.setsizemax (1024 * 1024 * 100);            Parse request, start reading data//iterator<fileitem> iter = (iterator<fileitem>) upload.getitemiterator (request);            Get all the form fields, which are now treated as Fileitem list<fileitem> Fileitems = upload.parserequest (request); Process the request in turn ITERATOR&LT;FILEITEM&GT            iter = Fileitems.iterator ();                while (Iter.hasnext ()) {Fileitem item = (Fileitem) iter.next ();                    if (Item.isformfield ()) {//if item is a normal form field, String name = Item.getfieldname ();                    String value = item.getstring ("UTF-8");                System.out.println ("The form domain name is:" +name+ "form field value is:" +value); } else {//If item is a File Upload form field//Get filename and path String filename = Item.get                    Name (); if (fileName! = null) {//If the file exists then upload the filename fullfile = new file (Item.getname ()                        ); if (fullfile.exists ()) {File Fileonserver = new File ("D:\\my documents\\" + fullfile.getname ()                            );                            Item.write (Fileonserver);                        System.out.println ("File" + fileonserver.getname () + "upload success");                 }   }                }            }        } 

  

Using ccommons-fileupload-1.2.1 to implement the upload, the implementation must include commons-io-1.4, the above for me to implement the method used to upload the file and the version of the package used.

Summary: The normal implementation of the file upload function, in the implementation process if the form is not configured enctype= "Multipart/form-data" element,

The upload file is an absolute local path, not a normal file.

Use the Reference API documentation in detail.

Java implementation File Upload

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.