Turn-fileupload on Java files

Source: Internet
Author: User


Original from: http://blog.csdn.net/ben1247/article/details/6552146

File upload in the Web application is very common, in the JSP environment to achieve file upload function is very easy, because there are many Java development of the file upload components, this article to commons-fileupload components for example, for JSP application to add File Upload function. The Common-fileupload component is one of Apache's open source projects that can be downloaded from http://jakarta.apache.org/commons/fileupload/.

This component enables you to upload one or more files at a time and limit the file size.


After downloading the zip package, copy the Commons-fileupload-1.0.jar to Tomcat's WebApps your webappweb-inflib, the directory does not exist please build your own directory.
Create a new Servlet:Upload.java for file uploads:
Import java.io.*;
Import java.util.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import org.apache.commons.fileupload.*;

public class Upload extends HttpServlet {

Private String Uploadpath = "C:upload"; directory where files are uploaded
Private String TempPath = "C:uploadtmp"; Temporary Files directory

public void DoPost (HttpServletRequest request,
HttpServletResponse response)
Throws IOException, Servletexception
{
}
}
In the Dopost () method, when the servlet receives a POST request from the browser, it implements the file upload. Here is the sample code:
public void DoPost (HttpServletRequest request,
HttpServletResponse response)
Throws IOException, Servletexception
{
try {
Diskfileupload fu = new Diskfileupload ();
Set maximum file size, this is 4MB
Fu.setsizemax (4194304);
Set the buffer size, this is 4KB
Fu.setsizethreshold (4096);
To set up a temporary directory:
Fu.setrepositorypath (TempPath);

Get all the files:
List Fileitems = fu.parserequest (request);
Iterator i = Fileitems.iterator ();
Process each file sequentially:
while (I.hasnext ()) {
Fileitem fi = (Fileitem) i.next ();
Gets the file name, which includes the path:
String fileName = Fi.getname ();
Where you can record user and file information
// ...
Write file, the tentative file name is A.txt, you can extract filename from filename:
Fi.write (New File (Uploadpath + "a.txt"));
}
}
catch (Exception e) {
Can jump to error page
}
}
If you want to read the specified upload folder in the configuration file, you can do so in the Init () method:
public void Init () throws Servletexception {
Uploadpath = .....
TempPath = .....
The folder is created automatically if it does not exist:
if (!new File (Uploadpath). Isdirectory ())
New File (Uploadpath). Mkdirs ();
if (!new File (TempPath). Isdirectory ())
New File (TempPath). Mkdirs ();
}
Compile the servlet, note that you want to specify CLASSPATH, and ensure that Commons-upload-1.0.jar and Tomcatcommonlibservlet-api.jar are included.
Configure the servlet, open Tomcatwebapps your webappweb-infweb.xml with Notepad, and then create a new one.
Typical configurations are as follows:
<?xml version= "1.0" encoding= "Iso-8859-1"?>
<! DOCTYPE Web-app
Public "-//sun Microsystems, INC.//DTD Web application 2.3//en"
"Http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>Upload</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
</web-app>
After you configure the servlet, start Tomcat and write a simple HTML test:
<form action= "FileUpload" method= "POST"
Enctype= "Multipart/form-data" Name= "Form1" >
<input type= "File" name= "file" >
<input type= "Submit" name= "submit" value= "Upload" >
</form>
Note action= "FileUpload" where FileUpload is the Url-pattern specified when the servlet is configured.


Here's the code for some prawn:

This upload is much better than smartupload. I was completely a byte of debugging out, not as much as the smartupload bug.
Call Method:
Upload up = new Upload ();
Up.init (Request);
/**
You can call Setsavedir (String Savedir) here, and set the save path
Call Setmaxfilesize (long size) to set the maximum number of bytes to upload files.
Call Settagfilename (String) to set the name of the file after the upload (valid only for the first file)
*/
Up. UploadFile ();

Then string[] names = Up.getfilename (); Get uploaded file name, file absolute path should be
Saved directory savedir+ "/" +names[i];
Can be passed up.getparameter ("field"); Get uploaded text or up.getparametervalues ("filed")
Gets the value of the same name field as multiple checkbox.
Try the others yourself.

Source: ____________________________________________________________
Package Com.inmsg.beans;

Import java.io.*;
Import java.util.*;
Import javax.servlet.*;
Import javax.servlet.http.*;

public class Upload {
Private String Savedir = "."; The path to save the file
Private String ContentType = ""; Document type
Private String charset = ""; Character
Private ArrayList tmpfilename = new ArrayList (); Data structure for temporary storage of file names
Private Hashtable parameter = new Hashtable (); Data structure that holds parameter names and values
Private ServletContext context; Program context, which is used to initialize the
private HttpServletRequest request; Instance used to pass in the Request object
Private String boundary = ""; Separator for memory data
private int len = 0; The length of bytes actually read from the inside each time
Private String querystring;
private int count; Total number of files uploaded
Private string[] FileName; Array of uploaded file names
Private Long MaxFileSize = 1024 * 1024 * 10; Maximum file upload byte;
Private String Tagfilename = "";

Public final void Init (HttpServletRequest request) throws Servletexception {
This.request = Request;
Boundary = Request.getcontenttype (). substring (30); Get the data delimiter in memory
QueryString = Request.getquerystring ();
}

Public String GetParameter (string s) {//used to get the parameter value of the specified field, overriding Request.getparameter (string s)
if (Parameter.isempty ()) {
return null;
}
Return (String) parameter.get (s);
}

Public string[] Getparametervalues (string s) {//used to get an array of arguments for the specified same name field, overriding Request.getparametervalues (string s)
ArrayList al = new ArrayList ();
if (Parameter.isempty ()) {
return null;
}
Enumeration E = Parameter.keys ();
while (E.hasmoreelements ()) {
String key = (string) e.nextelement ();
if (-1!= key.indexof (s + "| | | | | | | | |") | | key.equals (s)) {
Al.add (Parameter.get (key));
}
}
if (al.size () = = 0) {
return null;
}
string[] Value = new string[al.size ()];
for (int i = 0; i < value.length; i++) {
Value[i] = (String) al.get (i);
}
return value;
}

Public String getquerystring () {
return querystring;
}

public int GetCount () {
return count;
}

Public string[] GetFileName () {
return fileName;
}

public void Setmaxfilesize (long size) {
MaxFileSize = size;
}

public void Settagfilename (String filename) {
Tagfilename = filename;
}

public void Setsavedir (String savedir) {//Set the path to be saved by the upload file
This.savedir = Savedir;
File TestDir = new file (Savedir); To ensure that the directory exists, if not, create the new directory
if (!testdir.exists ()) {
Testdir.mkdirs ();
}
}

public void Setcharset (String charset) {//Set character set
This.charset = CharSet;
}

public Boolean UploadFile () throws Servletexception, IOException {//user-invoked upload method
Setcharset (Request.getcharacterencoding ());
Return UploadFile (Request.getinputstream ());
}

Private Boolean UploadFile (ServletInputStream servletinputstream) throws//main method of obtaining the data in the store
Servletexception, IOException {
String line = null;
byte[] buffer = new BYTE[256];
while (line = readLine (buffer, ServletInputStream, charset))!= null) {
if (Line.startswith ("content-disposition:form-data;")) {
int i = Line.indexof ("filename=");
if (I >= 0) {//If there is a filename= in the description within a section of the delimiter, the description is the encoded content of the file
String fName = GetFileName (line);
if (Fname.equals ("")) {
Continue
}
if (count = = 0 && tagfilename.length ()!= 0) {
String ext = fname.substring ((Fname.lastindexof (".") + 1));
FName = Tagfilename + "." + ext;
}
Tmpfilename.add (FName);
count++;
while (line = readLine (buffer, ServletInputStream, charset))!= null) {
if (Line.length () <= 2) {
Break
}
}
File F = new file (Savedir, fName);
FileOutputStream dos = new FileOutputStream (f);
Long size = 0l;
while (line = readLine (buffer, servletinputstream, NULL))!= null) {
if (Line.indexof (boundary)!=-1) {
Break
}
size = Len;
if (Size > MaxFileSize) {
throw new IOException ("file over" + MaxFileSize + "Byte!");
}
Dos.write (buffer, 0, Len);
}
Dos.close ();
}
else {//otherwise is the field-encoded content
String key = Getkey (line);
String value = "";
while (line = readLine (buffer, ServletInputStream, charset))!= null) {
if (Line.length () <= 2) {
Break
}
}
while (line = readLine (buffer, ServletInputStream, charset))!= null) {

if (Line.indexof (boundary)!=-1) {
Break
}
Value + = line;
}
Put (Key, Value.trim (), parameter);
}
}
}
if (querystring!= null) {
string[] Each = Split (QueryString, "&");
for (int k = 0; k < each.length; k++) {
String[] NV = Split (Each[k], "=");
if (nv.length = = 2) {
Put (Nv[0], nv[1], parameter);
}
}
}
FileName = new String[tmpfilename.size ()];
for (int k = 0; k < filename.length; k++) {
Filename[k] = (String) tmpfilename.get (k); Pour the temporary file name in the ArrayList into the data for the user to call
}
if (Filename.length = = 0) {
return false; If filename data is empty, no files are uploaded
}
return true;
}

private void put (string key, String value, Hashtable ht) {
if (!ht.containskey (key)) {
Ht.put (key, value);
}
else {//If you already have a key with the same name, you must rename the current key and note that you cannot have the same name as the key
try {
Thread.CurrentThread (). Sleep (1); In order to not generate two identical keys in the same MS
}
catch (Exception e) {}
Key + = "| | | | | | | | | |" + system.currenttimemillis ();
Ht.put (key, value);
}
}

/*
Call the Servletinputstream.readline (byte[] b,int offset,length) method, which reads a row from the ServletInputStream stream
To the specified byte array, in order to be able to hold a row, the byte[]b should not be less than 256, and in the overridden ReadLine, a member variable is called Len is
The number of bytes actually read (some rows are less than 256), the Len length byte should be written to the byte array instead of the entire byte[when the contents of the file are written.
Length, but the overridden method returns a string to parse the actual content and cannot return Len, so set Len as a member variable, and at each read operation
Assign the actual length to it.
That is, the data must be returned as a string to parse the start and end tags while the contents of the file are being processed, and also written to the file as byte[]
The output stream.
*/
Private String ReadLine (byte[] Linebyte,
ServletInputStream ServletInputStream, String CharSet) {
try {
Len = servletinputstream.readline (linebyte, 0, linebyte.length);
if (len = = 1) {
return null;
}
if (charset = = null) {
return new String (linebyte, 0, Len);
}
else {
return new String (linebyte, 0, Len, CharSet);
}

}
catch (Exception _ex) {
return null;
}

}

private string GetFileName (string line) {//separating the file name from the description string
if (line = = null) {
Return "";
}
int i = Line.indexof ("filename=");
line = line.substring (i + 9). Trim ();
i = Line.lastindexof ("");
if (I < 0 | | | I >= line.length ()-1) {
i = Line.lastindexof ("/");
if (Line.equals ("" ")) {
Return "";
}
if (I < 0 | | | I >= line.length ()-1) {
return line;
}
}
return line.substring (i + 1, line.length ()-1);
}

private string Getkey (string line) {//separating field names from the description string
if (line = = null) {
Return "";
}
int i = Line.indexof ("name=");
line = line.substring (i + 5). Trim ();
Return line.substring (1, Line.length ()-1);
}

public static string[] Split (string strob, string mark) {
if (Strob = = null) {
return null;
}
StringTokenizer st = new StringTokenizer (Strob, Mark);
ArrayList tmp = new ArrayList ();
while (St.hasmoretokens ()) {
Tmp.add (St.nexttoken ());
}
string[] Strarr = new string[tmp.size ()];
for (int i = 0; i < tmp.size (); i++) {
Strarr[i] = (String) tmp.get (i);
}
return strarr;
}
Download is actually very simple, as long as the following processing, there will be no problem.

public void DownLoad (String filepath,httpservletresponse response,boolean isonline)
Throws exception{
File F = new file (FilePath);
if (!f.exists ()) {
Response.senderror (404, "File not found!");
Return
}
Bufferedinputstream br = new Bufferedinputstream (new FileInputStream (f));
byte[] buf = new byte[1024];
int len = 0;

Response.reset (); Very important
if (isonline) {//Online open mode
URL u = new URL ("file:///" +filepath);
Response.setcontenttype (U.openconnection (). getContentType ());
Response.setheader ("content-disposition", "inline; Filename= "+f.getname ());
File name should be encoded into UTF-8
}
else{//Pure Download mode
Response.setcontenttype ("Application/x-msdownload");
Response.setheader ("Content-disposition", "attachment; Filename= "+ f.getname ());
}
OutputStream out = Response.getoutputstream ();
while (len = Br.read (buf)) >0)
Out.write (Buf,0,len);
Br.close ();
Out.close ();
}

Related Article

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.