📄 fileupload.java
字号:
}
// A real file's contents are written to disk
else {
File f = new File(dir + File.separator + filename);
out = new BufferedOutputStream(new FileOutputStream(f), 8 * 1024);
}
byte[] bbuf = new byte[100 * 1024]; // 100K
int result;
String line;
// ServletInputStream.readLine() has the annoying habit of
// adding a \r\n to the end of the last line.
// Since we want a byte-for-byte transfer, we have to cut those chars.
boolean rnflag = false;
while ((result = in.readLine(bbuf, 0, bbuf.length)) != -1) {
// Check for boundary
if (result > 2 && bbuf[0] == '-' && bbuf[1] == '-') { // quick pre-check
line = new String(bbuf, 0, result, "ISO-8859-1");
//line = new String(bbuf, 0, result, "gb2312");
if (line.startsWith(boundary)) break;
}
// Are we supposed to write \r\n for the last iteration?
if (rnflag) {
out.write('\r'); out.write('\n');
rnflag = false;
}
// Write the buffer, postpone any ending \r\n
if (result >= 2 &&
bbuf[result - 2] == '\r' &&
bbuf[result - 1] == '\n') {
out.write(bbuf, 0, result - 2); // skip the last 2 chars
rnflag = true; // make a note to write them on the next iteration
}
else {
out.write(bbuf, 0, result);
}
}
out.flush();
out.close();
}
// Extracts and returns the boundary token from a line.
//
private String extractBoundary(String line) {
// Use lastIndexOf() because IE 4.01 on Win98 has been known to send the
// "boundary=" string multiple times. Thanks to David Wall for this fix.
int index = line.lastIndexOf("boundary=");
if (index == -1) {
return null;
}
String boundary = line.substring(index + 9); // 9 for "boundary="
// The real boundary is always preceeded by an extra "--"
boundary = "--" + boundary;
return boundary;
}
// Extracts and returns disposition info from a line, as a String array
// with elements: disposition, name, filename. Throws an IOException
// if the line is malformatted.
//
private String[] extractDispositionInfo(String line) throws IOException {
// Return the line's data as an array: disposition, name, filename
String[] retval = new String[3];
// Convert the line to a lowercase string without the ending \r\n
// Keep the original line for error messages and for variable names.
String origline = line;
line = origline.toLowerCase();
// Get the content disposition, should be "form-data"
int start = line.indexOf("content-disposition: ");// total 21
int end = line.indexOf(";");
if (start == -1 || end == -1) {
throw new IOException("Content disposition corrupt: " + origline);
}
String disposition = line.substring(start + 21, end);
if (!disposition.equals("form-data")) {
throw new IOException("Invalid content disposition: " + disposition);
}
// Get the field name
start = line.indexOf("name=\"", end); // start at last semicolon
end = line.indexOf("\"", start + 7); // skip name=\"
if (start == -1 || end == -1) {
throw new IOException("Content disposition corrupt: " + origline);
}
String name = origline.substring(start + 6, end);
// Get the filename, if given
String filename = null;
start = line.indexOf("filename=\"", end + 2); // start after name
end = line.indexOf("\"", start + 10); // skip filename=\"
if (start != -1 && end != -1) { // note the !=
filename = origline.substring(start + 10, end);
// The filename may contain a full path. Cut to just the filename.
int slash =
Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
if (slash > -1) {
filename = filename.substring(slash + 1); // past last slash
}
if (filename.equals("")) filename = NO_FILE; // sanity check
}
// Return a String array: disposition, name, filename
retval[0] = disposition;
retval[1] = name;
retval[2] = filename;
return retval;
}
// Extracts and returns the content type from a line, or null if the
// line was empty. Throws an IOException if the line is malformatted.
//
private String extractContentType(String line) throws IOException {
String contentType = null;
// Convert the line to a lowercase string
String origline = line;
line = origline.toLowerCase();
// Get the content type, if any
if (line.startsWith("content-type")) {
int start = line.indexOf(" ");
if (start == -1) {
throw new IOException("Content type corrupt: " + origline);
}
contentType = line.substring(start + 1);
}
else if (line.length() != 0) { // no content type, so should be empty
throw new IOException("Malformed line after disposition: " + origline);
}
return contentType;
}
/**
*
*Get the servlet server path ,For instance :======>"c:\jswdk"
*/
public String getServletPath() throws IOException
{
File f = new File(".");
String path = f.getAbsolutePath();
path = path.substring(0, path.length()-2); //delete '\.'
return path;
}
/**
*get the absolute path from relative path
*
*/
public String getDirectory(String strDir) throws IOException
{
if(strDir.compareTo(".") == 0) //path of jsp
strDir = "";
String absDir = getServletPath() + strDir;
absDir = EscapePathString(absDir);
return absDir;
}
public boolean makeRelativeDir(String strDir) throws IOException
{
String absDir = getDirectory(strDir);
dir = new File(absDir);
if(!dir.exists() || dir.isFile())
dir.mkdirs();
if (!dir.canWrite())
{
System.out.println("Please check directory " + dir + " exists and is writable");
return false;
}
return true;
}
public boolean makeAbsoluteDir(String strDir) throws IOException
{
dir = new File(strDir);
if(!dir.exists() || dir.isFile())
dir.mkdirs();
if (!dir.canWrite())
{
System.out.println("Please check directory " + dir + " exists and is writable");
return false;
}
return true;
}
/**
*Because the different path format in different OS(Winddows and Unix)
*So use the File.separator, change '\' and '/' into File.separator
*/
public String EscapePathString(String str) throws IOException
{
int len=str.length();
String tmpstr="";
char char_arr[]=str.toCharArray();
String chrar="";
for(int i=0;i<len;i++)
{
chrar = String.valueOf(char_arr[i]);
if(chrar.equals("\\")==true || chrar.equals("/")==true)
tmpstr=tmpstr + File.separator;
else
tmpstr=tmpstr+char_arr[i];
}
return tmpstr;
}
/**
* Get a file object from relative path
*
*/
public File getFilebyName(String fileName) throws IOException
{
String pathFile = getDirectory(fileName);
File f = null;
f = new File(pathFile);
if(f.exists())
return f;
else
return null;
}
/**
* Get a file object from absolute path
*
*/
public File getFilebyPath(String filePath) throws IOException
{
File f = null;
f = new File(filePath);
if(f.exists())
return f;
else
return null;
}
public boolean deleteFile(File f) throws IOException
{
if ( f == null )
return false;
/* String pathFile = f.getAbsolutePath();
try
{
System.getSecurityManager().checkDelete(pathFile);
}
catch(SecurityException se)
{
System.out.println(se.getMessage());
return false;
}
try
{
f.delete();
}
catch(Exception e)
{
System.out.println(e.getMessage());
return false;
}
*/
f.delete();
return true;
}
}
// A class to hold information about an uploaded file.
//
class UploadedFile {
private String dir;
private String filename;
private String type;
UploadedFile(String dir, String filename, String type) {
this.dir = dir;
this.filename = filename;
this.type = type;
}
public String getContentType() {
return type;
}
public String getFilesystemName() {
return filename;
}
public File getFile() {
if (dir == null || filename == null) {
return null;
}
else {
return new File(dir + File.separator + filename);
}
}
}
// A class to aid in reading multipart/form-data from a ServletInputStream.
// It keeps track of how many bytes have been read and detects when the
// Content-Length limit has been reached. This is necessary since some
// servlet engines are slow to notice the end of stream.
//
// Mac users: The Mac doesn't like class names which exceed 32 characters
// (including the ".class") so while this class is usable from a JAR
// anywhere, it won't compile on a Mac.
//
class MultipartInputStreamHandler {
ServletInputStream in;
int totalExpected;
int totalRead = 0;
byte[] buf = new byte[8 * 1024];
public MultipartInputStreamHandler(ServletInputStream in,
int totalExpected) {
this.in = in;
this.totalExpected = totalExpected;
}
// Reads the next line of input. Returns null to indicate the end
// of stream.
//
public String readLine() throws IOException {
StringBuffer sbuf = new StringBuffer();
int result;
String line;
do {
result = this.readLine(buf, 0, buf.length); // this.readLine() does +=
if (result != -1) {
sbuf.append(new String(buf, 0, result, "ISO-8859-1"));
//sbuf.append(new String(buf, 0, result, "gb2312"));
}
} while (result == buf.length); // loop only if the buffer was filled
if (sbuf.length() == 0) {
return null; // nothing read, must be at the end of stream
}
sbuf.setLength(sbuf.length() - 2); // cut off the trailing \r\n
return sbuf.toString();
}
// A pass-through to ServletInputStream.readLine() that keeps track
// of how many bytes have been read and stops reading when the
// Content-Length limit has been reached.
//
public int readLine(byte b[], int off, int len) throws IOException {
if (totalRead >= totalExpected) {
return -1;
}
else {
if (len > (totalExpected - totalRead)) {
len = totalExpected - totalRead; // keep from reading off end
}
int result = in.readLine(b, off, len);
if (result > 0) {
totalRead += result;
}
return result;
}
}
}
// Class to filters MacBinary files to normal files on the fly
// Optimized for speed more than readability
class MacBinaryDecoderOutputStream extends FilterOutputStream {
int bytesFiltered = 0;
int dataForkLength = 0;
public MacBinaryDecoderOutputStream(OutputStream out) {
super(out);
}
public void write(int b) throws IOException {
// Bytes 83 through 86 are a long representing the data fork length
// Check <= 86 first to short circuit early in the common case
if (bytesFiltered <= 86 && bytesFiltered >= 83) {
int leftShift = (86 - bytesFiltered) * 8;
dataForkLength = dataForkLength | (b & 0xff) << leftShift;
}
// Bytes 128 up to (128 + dataForkLength - 1) are the data fork
else if (bytesFiltered < (128 + dataForkLength) && bytesFiltered >= 128) {
out.write(b);
}
bytesFiltered++;
}
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
// If the write is for content past the end of the data fork, ignore
if (bytesFiltered >= (128 + dataForkLength)) {
bytesFiltered += len;
}
// If the write is entirely within the data fork, write it directly
else if (bytesFiltered >= 128 &&
(bytesFiltered + len) <= (128 + dataForkLength)) {
out.write(b, off, len);
bytesFiltered += len;
}
// Otherwise, do the write a byte at a time to get the logic above
else {
for (int i = 0 ; i < len ; i++) {
write(b[off + i]);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -