📄 fileupload.java
字号:
//File Upload from Page
//<FORM NAME="????" ACTION="*.jsp" METHOD=POST ENCTYPE="multipart/form-data">
/***************How to use this class***********
The class must be used in pages and get the 'request' as a parameter
You must make a directory firstly and upload the file
There are two ways to make a directory
One use the makeAbsoluteDir() make a absolute dir in server
The other use the makeRelativeDir() make a relative dir undre the path of jsp in server
Then You can use uploadFile(request) to upload file
*******************/
package tools.util;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
public class FileUpload
{
public String saveName="";
private static final int DEFAULT_MAX_POST_SIZE = 1024 * 1024; // 1 Meg
private static final String NO_FILE = "unknown";
private static HttpServletRequest req;
private static File dir;
private static int encodedir;
private static int maxSize;
private static Hashtable parameters = new Hashtable(); // name - Vector of values
private static Hashtable files = new Hashtable(); // name - UploadedFile
public static void main(String argv[])
{
}
public FileUpload()
{
req = null;
}
public void uploadFile(HttpServletRequest request, int direncode) throws IOException
{
uploadFile(request, DEFAULT_MAX_POST_SIZE, direncode);
}
public void uploadFile(HttpServletRequest request, int maxPostSize, int direncode) throws IOException
{
req = request;
maxSize = maxPostSize;
encodedir = direncode;
readRequest();
}
public static void clearFiles()
{
files.clear();
}
public static void clearParameters()
{
parameters.clear();
}
/**
* Returns the names of all the parameters as an Enumeration of
* Strings. It returns an empty Enumeration if there are no parameters.
*
* @return the names of all the parameters as an Enumeration of Strings
*/
public Enumeration getParameterNames() {
return parameters.keys();
}
/**
* Returns the names of all the uploaded files as an Enumeration of
* Strings. It returns an empty Enumeration if there are no uploaded
* files. Each file name is the name specified by the form, not by
* the user.
*
* @return the names of all the uploaded files as an Enumeration of Strings
*/
public Enumeration getFileNames() {
return files.keys();
}
/**
* Returns the value of the named parameter as a String, or null if
* the parameter was not sent or was sent without a value. The value
* is guaranteed to be in its normal, decoded form. If the parameter
* has multiple values, only the last one is returned (for backward
* compatibility). For parameters with multiple values, it's possible
* the last "value" may be null.
*
* @param name the parameter name
* @return the parameter value
*/
public String getParameter(String name) {
try {
Vector values = (Vector)parameters.get(name);
if (values == null || values.size() == 0) {
return null;
}
String value = (String)values.elementAt(values.size() - 1);
return value;
}
catch (Exception e) {
return null;
}
}
/**
* Returns the values of the named parameter as a String array, or null if
* the parameter was not sent. The array has one entry for each parameter
* field sent. If any field was sent without a value that entry is stored
* in the array as a null. The values are guaranteed to be in their
* normal, decoded form. A single value is returned as a one-element array.
*
* @param name the parameter name
* @return the parameter values
*/
public String[] getParameterValues(String name) {
try {
Vector values = (Vector)parameters.get(name);
if (values == null || values.size() == 0) {
return null;
}
String[] valuesArray = new String[values.size()];
values.copyInto(valuesArray);
return valuesArray;
}
catch (Exception e) {
return null;
}
}
/**
* Returns the filesystem name of the specified file, or null if the
* file was not included in the upload. A filesystem name is the name
* specified by the user. It is also the name under which the file is
* actually saved.
*
* @param name the file name
* @return the filesystem name of the file
*/
public String getFilesystemName(String name) {
try {
UploadedFile file = (UploadedFile)files.get(name);
return file.getFilesystemName(); // may be null
}
catch (Exception e) {
return null;
}
}
/**
* Returns the content type of the specified file (as supplied by the
* client browser), or null if the file was not included in the upload.
*
* @param name the file name
* @return the content type of the file
*/
public String getContentType(String name) {
try {
UploadedFile file = (UploadedFile)files.get(name);
return file.getContentType(); // may be null
}
catch (Exception e) {
return null;
}
}
/**
* Returns a File object for the specified file saved on the server's
* filesystem, or null if the file was not included in the upload.
*
* @param name the file name
* @return a File object for the named file
*/
public File getFile(String name) {
try {
UploadedFile file = (UploadedFile)files.get(name);
return file.getFile(); // may be null
}
catch (Exception e) {
return null;
}
}
/**
* The workhorse method that actually parses the request. A subclass
* can override this method for a better optimized or differently
* behaved implementation.
*
* @exception IOException if the uploaded content is larger than
* <tt>maxSize</tt> or there's a problem parsing the request
*/
protected void readRequest() throws IOException {
// Check the content length to prevent denial of service attacks
int length = req.getContentLength();
if (length > maxSize) {
throw new IOException("Posted content length of " + length +
" exceeds limit of " + maxSize);
}
// Check the content type to make sure it's "multipart/form-data"
// Access header two ways to work around WebSphere oddities
String type = null;
String type1 = req.getHeader("Content-Type");
String type2 = req.getContentType();
// If one value is null, choose the other value
if (type1 == null && type2 != null) {
type = type2;
}
else if (type2 == null && type1 != null) {
type = type1;
}
// If neither value is null, choose the longer value
else if (type1 != null && type2 != null) {
type = (type1.length() > type2.length() ? type1 : type2);
}
if (type == null ||
!type.toLowerCase().startsWith("multipart/form-data")) {
throw new IOException("Posted content type isn't multipart/form-data");
}
// Get the boundary string; it's included in the content type.
// Should look something like "------------------------12012133613061"
String boundary = extractBoundary(type);
if (boundary == null) {
throw new IOException("Separation boundary was not specified");
}
// Construct the special input stream we'll read from
MultipartInputStreamHandler in =
new MultipartInputStreamHandler(req.getInputStream(), length);
// Read the first line, should be the first boundary
String line = in.readLine();
if (line == null) {
throw new IOException("Corrupt form data: premature ending");
}
// Verify that the line is the boundary
if (!line.startsWith(boundary)) {
throw new IOException("Corrupt form data: no leading boundary");
}
// Now that we're just beyond the first boundary, loop over each part
boolean done = false;
while (!done) {
done = readNextPart(in, boundary);
}
}
/**
* A utility method that reads an individual part. Dispatches to
* readParameter() and readAndSaveFile() to do the actual work. A
* subclass can override this method for a better optimized or
* differently behaved implementation.
*
* @param in the stream from which to read the part
* @param boundary the boundary separating parts
* @return a flag indicating whether this is the last part
* @exception IOException if there's a problem reading or parsing the
* request
*
* @see readParameter
* @see readAndSaveFile
*/
protected boolean readNextPart(MultipartInputStreamHandler in,
String boundary) throws IOException {
// Read the first line, should look like this:
// content-disposition: form-data; name="field1"; filename="file1.txt"
String line = in.readLine();
if (line == null) {
// No parts left, we're done
return true;
}
else if (line.length() == 0) {
// IE4 on Mac sends an empty line at the end; treat that as the end.
// Thanks to Daniel Lemire and Henri Tourigny for this fix.
return true;
}
// Parse the content-disposition line
String[] dispInfo = extractDispositionInfo(line);
String disposition = dispInfo[0];
String name = dispInfo[1];
String filename = dispInfo[2];
// Now onto the next line. This will either be empty
// or contain a Content-Type and then an empty line.
line = in.readLine();
if (line == null) {
// No parts left, we're done
return true;
}
// Get the content type, or null if none specified
String contentType = extractContentType(line);
if (contentType != null) {
// Eat the empty line
line = in.readLine();
if (line == null || line.length() > 0) { // line should be empty
throw new
IOException("Malformed line after content type: " + line);
}
}
else {
// Assume a default content type
contentType = "application/octet-stream";
}
// Now, finally, we read the content (end after reading the boundary)
if (filename == null) {
// This is a parameter, add it to the vector of values
String value = readParameter(in, boundary);
if (value.equals("")) {
value = null; // treat empty strings like nulls
}
if (value != null)
value = new String(value.getBytes("iso-8859-1"));
/**
* Snow: get parameter and create upload file path
*/
if(name != null && name.equalsIgnoreCase("filepath") && value != null){
String pathfile = null;
if(encodedir == 1)
pathfile = Decode.Decrypt(value);
else
pathfile = value;
makeAbsoluteDir(pathfile);
}
Vector existingValues = (Vector)parameters.get(name);
if (existingValues == null) {
existingValues = new Vector();
parameters.put(name, existingValues);
}
existingValues.addElement(value);
}
else {
if (filename.equals(NO_FILE)) {
files.put(name, new UploadedFile(null, null, null));
}else{
// This is a file
//readAndSaveFile(in, boundary, filename, contentType);
//readAndSaveFile(in, boundary, saveName+new String(filename.getBytes("iso-8859-1")), contentType);
String tmpName=new String(filename.getBytes("iso-8859-1"));
readAndSaveFile(in, boundary, saveName+tmpName.substring(tmpName.lastIndexOf("."),tmpName.length()), contentType);
files.put(name, new UploadedFile(dir.toString(), filename, contentType));
}
}
return false; // there's more to read
}
/**
* A utility method that reads a single part of the multipart request
* that represents a parameter. A subclass can override this method
* for a better optimized or differently behaved implementation.
*
* @param in the stream from which to read the parameter information
* @param boundary the boundary signifying the end of this part
* @return the parameter value
* @exception IOException if there's a problem reading or parsing the
* request
*/
protected String readParameter(MultipartInputStreamHandler in,
String boundary) throws IOException {
StringBuffer sbuf = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
if (line.startsWith(boundary)) break;
sbuf.append(line + "\r\n"); // add the \r\n in case there are many lines
}
if (sbuf.length() == 0) {
return null; // nothing read
}
sbuf.setLength(sbuf.length() - 2); // cut off the last line's \r\n
return sbuf.toString(); // no URL decoding needed
}
/**
* A utility method that reads a single part of the multipart request
* that represents a file, and saves the file to the given directory.
* A subclass can override this method for a better optimized or
* differently behaved implementation.
*
* @param in the stream from which to read the file
* @param boundary the boundary signifying the end of this part
* @param dir the directory in which to save the uploaded file
* @param filename the name under which to save the uploaded file
* @exception IOException if there's a problem reading or parsing the
* request
*/
protected void readAndSaveFile(MultipartInputStreamHandler in,
String boundary,
String filename,
String contentType) throws IOException {
OutputStream out = null;
// A filename of NO_FILE means no file was sent, so just read to the
// next boundary and ignore the empty contents
if (filename.equals(NO_FILE)) {
out = new ByteArrayOutputStream(); // write to nowhere
}
if(dir == null)
dir = new File("/uploadfile");
// A MacBinary file goes through a decoder
else if (contentType.equals("application/x-macbinary")){
File f = new File(dir + File.separator + filename);
out = new MacBinaryDecoderOutputStream(
new BufferedOutputStream(
new FileOutputStream(f), 8 * 1024));
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -