Java Operation file Bulk upload

Source: Internet
Author: User

Package com.fangdi.landaudit.process.util;

Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.PrintWriter;
Import Java.util.Iterator;
Import java.util.List;

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.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFile extends HttpServlet {

/**
*
*/
Private static final long serialversionuid = 1L;

Public UploadFile () {
Super ();
}

/**
* Destruction of the servlet. <br>
*/
public void Destroy () {
Super.destroy (); Just puts "destroy" string in log
Put your code here
}

public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {

Response.setcontenttype ("text/html");
PrintWriter out = Response.getwriter ();
Out
. println ("<! DOCTYPE HTML public \-//w3c//dtd HTML 4.01 transitional//en\ ">");
Out.println ("<HTML>");
Out.println ("Out.println ("<BODY>");
Out.print ("This is");
Out.print (This.getclass ());
Out.println (", using the Get Method");
Out.println ("</BODY>");
Out.println ("</HTML>");
Out.flush ();
Out.close ();
}

public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {

Creates a file-processing factory that is used to generate Fileitem objects.

Diskfileitemfactory difactory = new Diskfileitemfactory ();

Sets the cache size, and if the upload file exceeds the cache size, the temporary directory is used as the cache.

Difactory.setsizethreshold (1024 * 1024);

Set up temporary directories for processing factory caches, and files in this directory need to be manually removed.

String dir = This.getservletcontext (). Getrealpath ("/");

File Filedir = new file (dir + "filetemp");

if (!filedir.exists ())

Filedir.mkdir ();

Difactory.setrepository (Filedir);

Set the directory in which the file is actually saved

String Userdir = dir + "files";

File Fudir = new file (Userdir);

if (!fudir.exists ())

Fudir.mkdir ();

Creates the parser for the request, which encapsulates the data into the Fileitem object.

Servletfileupload SFU = new Servletfileupload (difactory);

Sfu.setheaderencoding ("Utf-8");


Resolves data saved in request and returns to the list collection

List List = null;

try {

List = Sfu.parserequest (request);

catch (Fileuploadexception e) {

E.printstacktrace ();

}

Traverse the list collection, remove the Fileitem object for each entry, and get the data separately

for (Iterator it = List.iterator (); It.hasnext ();) {

Fileitem fi = (Fileitem) it.next ();

if (Fi.isformfield ()) {

System.out.println (Fi.getfieldname ());

System.out.println (Fi.getstring ());

} else {

Because the client sends a file to the server that is the full path to the client, we need only the filename

String filename = Fi.getname ();

int index = filename.lastindexof ("\ \");

if (index!=-1) {

filename = filename.substring (index + 1);

Write a file to the server

InputStream in = Fi.getinputstream ();

FileOutputStream fos = new FileOutputStream (Fudir + "/"
+ filename);

byte[] buf = new byte[1024];

int len =-1;

while (len = In.read (buf))!=-1) {

Fos.write (buf, 0, Len);

}

Close the stream

if (in!= null) {

try {

In.close ();

finally {

if (FOS!= null)

Fos.close ();
}
}
}
}

}

}

public void Init () throws Servletexception {
Put your code here
}

}

Page

<body topmargin= "0" leftmargin= "0" rightmargin= "0" marginheight= "0" marginwidth= "0" >
<form name= "Form2" enctype= "Multipart/form-data" method= "post" action= "<%=path%>/servlet/uploadfile" >
<table border= "0" cellpadding= "0" cellspacing= "0" >
<tr>
<td><b> Please select the uploaded file:</b>
<input id= "File" name= "file" type= "file" size= "><input type=" button "value=" Add "onclick=" AddRow () ">
</td>
</tr>
<tr style= "Display:none" id= "Mytr" >
<td><b> Please select the uploaded file:</b>
<input id= "File" name= "file" type= "file" size= "><input type=" button "value=" delete "onclick=" delrow (This) " >
</td>
</tr>
</table>
<input name= "Submit" type= "Submit" class= "Btn_grey" value= "Confirm" >
<input name= "Submit2" type= "button" class= "Btn_grey" onclick= "Window.close ()" value= "Off" >
</form>
</body>
<script type= "Text/javascript" >
function AddRow ()
{
var tr = document.getElementById ("Mytr");
var con = Tr.clonenode (true);
Con.removeattribute ("style");
Tr.parentNode.insertAdjacentElement ("BeforeEnd", con);
}
function Delrow (obj)
{
var Tr=obj.parentnode.parentnode;
Tr.parentNode.removeChild (TR);
}
</script>
Commons-fileupload-1.2.1.jar Commons-io-1.4.jar

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.