標籤:
之前介紹了只使用一段代碼實現上傳檔案的方法。最近又試了幾次,才發現這個是有問題的。
例如,要上傳原檔案如下的檔案:
使用jsp上傳後發現檔案變成了下面這個樣子,圖片下面的像素沒有了。
然後我又用common-upload1.2試了下,能夠正常上傳,檔案不會變樣。怎麼會這個樣子呢?
要解決這個問題先瞭解下背景知識,瀏覽器發http請求時一般的post方法會把輸入控制項的name與value拼成一個字串做為請求體傳給伺服器。而對於method="post" enctype="multipart/form-data"這種上傳檔案的http請求的要求標頭中加了類似這樣的資訊:
Content-Length 5137
Content-Type multipart/form-data; boundary=---------------------------203012335616103
這個boundary代表請求體裡的分隔字元,就是整個請求體以這個分隔字元的值把真正的檔案內容包起來。
請求體是如下格式:
-----------------------------221842651231148
Content-Disposition: form-data; name="upfile"; filename="srcfile (2).jpg"
Content-Type: image/jpeg
<!—這裡上傳檔案內容(位元組數組)—》
-----------------------------221842651231148
可以看到分隔字元裡的內容除了檔案位元組,還在檔案內容之前加一些檔案基本資料。
下面分析下為什麼jsp沒有正確上傳檔案,先看看jsp上傳代碼:
1.取得contextLength的所有位元組數組
in = new DataInputStream(request.getInputStream());
int dataLength = request.getContentLength();
while (totalBytesRead < dataLength) {
byteRead = in.read(dataBytes, totalBytesRead,
dataLength);
totalBytesRead += byteRead;
}
2.取檔案的開始位置與結束位置
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation))
.getBytes()).length;
3.把開始位置到結束位置的位元組數群組轉換為檔案,輸出到磁碟。
FileOutputStream fos=new FileOutputStream(fileName)
fos.write(dataBytes, startPos, (endPos - startPos));
fileOut.close();
那麼common-upload又怎麼做的呢,代碼較多,這裡只分析一些關鍵邏輯代碼:
1. 解析檔案,並要求標頭中取出分隔字元
//rquest對象轉為FileItemStreamIterator對象
org.apache.commons.fileupload.servlet.ServletFileUpload[line:146]
FileItemIterator fii = new ServletFileUpload().getItemIterator(request);
//取Header
org.apache.commons.fileupload.FileUploadBase[line:976]
FileItemHeaders headers = getParsedHeaders(multi.readHeaders());
//取Header裡的ContentType裡的分隔字元
org.apache.commons.fileupload.FileUploadBase[line:397]
protected byte[] getBoundary(String contentType) {
2. 找出請求體裡分隔字元之間的有效資料。
//找分隔字元的方法如下,buffer裡的位元組要與boundary裡的位元組完全一樣才認為是分隔字元:
org.apache.commons.fileupload.MultipartStream[line:708]
protected int findSeparator() {
int first;
int match = 0;
int maxpos = tail - boundaryLength;
for (first = head;
(first <= maxpos) && (match != boundaryLength);
first++) {
first = findByte(boundary[0], first);
if (first == -1 || (first > maxpos)) {
return -1;
}
for (match = 1; match < boundaryLength; match++) {
if (buffer[first + match] != boundary[match]) {
break;
}
}
}
if (match == boundaryLength) {
return first - 1;
}
return -1;
}
3. 把分隔字元分隔的每段有效資料匯總成為一個位元組數組,最後形成檔案。這裡使用了如下的類和方法來匯總:
org.apache.commons.fileupload.MultipartStream[line:784]
public class ItemInputStream extends InputStream implements Closeable
public int read(byte[] b, int off, int len) throws IOException {
if (closed) {
throw new FileItemStream.ItemSkippedException();
}
if (len == 0) {
return 0;
}
int res = available();
if (res == 0) {
res = makeAvailable();
if (res == 0) {
return -1;
}
}
res = Math.min(res, len);
System.arraycopy(buffer, head, b, off, res);
head += res;
total += res;
return res;
}
最後total數就是最終的檔案位元組數了,再用FileOutputStream即可寫為檔案。這個available函數和怎麼覆蓋InputStream的還沒弄得太明白,還需進一步瞭解流的底層流程。
由上面可以看出jsp上傳代碼錯誤主要是分隔字元識別不正確導致的。
學習common-upload源碼,理解上傳原理