HTTP 檔案上傳採用 multipart/form-data 編碼,伺服器需解析請求輸入流,分離表單欄位與檔案內容。本範例示範手動解析流程,教學用途為主,生產環境建議使用成熟庫 (Apache Commons FileUpload、Servlet 3.0 @MultipartConfig)。
package yuanyifileup;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.PageContext;
public class yuanyifileup {
private ServletRequest request;
private ServletResponse response;
private ServletConfig config;
ServletInputStream DATA;
int FormSize;
File f1;
FileOutputStream os;
DataInputStream is;
String filename;
byte[] b;
byte t;
boolean flag = false;
public yuanyifileup() {}
// 以 ServletConfig 初始化
public void initialize(ServletConfig config, HttpServletRequest request, HttpServletResponse response) throws IOException {
this.request = request;
this.response = response;
this.config = config;
DATA = request.getInputStream();
FormSize = request.getContentLength();
}
// 以 PageContext 初始化 (JSP 中較方便)
public void initialize(PageContext pageContext) throws IOException {
request = pageContext.getRequest();
response = pageContext.getResponse();
config = pageContext.getServletConfig();
DATA = request.getInputStream();
FormSize = request.getContentLength();
}
// 設定儲存檔案路徑
public boolean setFilename(String s) {
try {
f1 = new File(s);
os = new FileOutputStream(f1);
} catch(IOException e) { return false; }
return true;
}
// 讀取完整請求內容至 byte 陣列
public void getByte() {
int i = 0;
try {
is = new DataInputStream(DATA);
b = new byte[FormSize];
while (true) {
try {
t = is.readByte();
b[i] = t;
i++;
} catch(EOFException e) { break; }
}
is.close();
} catch(IOException e) {}
}
// 解析 multipart 資料並儲存檔案
public boolean save() {
int i = 0, start1 = 0, start2 = 0;
String temp = "";
if (!flag) { getByte(); flag = true; }
try {
temp = new String(b, "ISO8859_1");
} catch(UnsupportedEncodingException e) { return false; }
start1 = temp.indexOf("image/");
temp = temp.substring(start1);
start1 = temp.indexOf("\r\n\r\n");
temp = temp.substring(start1 + 4);
start2 = temp.indexOf("\r\n");
if (start2 != -1) temp = temp.substring(0, start2);
try {
byte[] img = temp.getBytes("ISO8859_1");
for (i = 0; i < img.length; i++) { os.write(img[i]); }
os.close();
} catch(IOException e) { return false; }
return true;
}
}
<%@ page import="yuanyifileup.*" %>
<%
yuanyifileup up = new yuanyifileup();
up.initialize(pageContext);
if (up.setFilename("D:/upload/test.jpg")) {
if (up.save()) out.println("上傳成功");
else out.println("上傳失敗: " + up.getErrorMessage());
}
%>
image/ 開頭,通用性差。<form method="post" enctype="multipart/form-data"> 搭配 Servlet 3.0 request.getPart() 或 Commons FileUpload。