Struts 2 文件上傳依賴 commons-fileupload 與 commons-io,透過 FileUploadInterceptor 自動處理 multipart/form-data 請求。
public class UploadAction extends ActionSupport {
private File upload; // 上傳檔案
private String uploadContentType; // 檔案 MIME 類型
private String uploadFileName; // 原始檔名
// Getter/Setter 省略
@Override
public String execute() {
String destPath = ServletActionContext.getServletContext().getRealPath("/uploads");
File destDir = new File(destPath);
if (!destDir.exists()) destDir.mkdirs();
File destFile = new File(destDir, uploadFileName);
try {
Files.copy(upload.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
addActionMessage("上傳成功:" + uploadFileName);
return SUCCESS;
} catch (IOException e) {
addActionError("上傳失敗:" + e.getMessage());
return ERROR;
}
}
}
<s:form action="upload" enctype="multipart/form-data">
<s:file name="upload" label="選擇檔案"/>
<s:submit value="上傳"/>
</s:form>
<action name="upload" class="com.example.UploadAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">10485760</param> <!-- 10MB -->
<param name="allowedTypes">image/jpeg,image/png,application/pdf</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
<result name="success">/upload_result.jsp</result>
<result name="error">/upload_error.jsp</result>
</action>
// UploadAction-validation.xml
<validators>
<field name="upload">
<field-validator type="required">
<message>請選擇要上傳的檔案</message>
</field-validator>
<field-validator type="fieldexpression">
<param name="expression">uploadContentType.startsWith('image/')</param>
<message>僅允許圖片檔案</message>
</field-validator>
</field>
</validators>
<script>
function validateUpload() {
var fileInput = document.getElementById('upload');
var file = fileInput.files[0];
if (!file) { alert('請選擇檔案'); return false; }
if (file.size > 10 * 1024 * 1024) { alert('檔案不可超過 10MB'); return false; }
var allowed = ['image/jpeg', 'image/png', 'application/pdf'];
if (!allowed.includes(file.type)) { alert('僅支援 JPG、PNG、PDF'); return false; }
return true;
}
</script>
<s:form action="upload" enctype="multipart/form-data" onsubmit="return validateUpload()"> ... </s:form>
List<File> uploads,JSP 多個 <s:file name="uploads"/>@MultipartConfig + AJAX 輪詢或 WebSocketStruts 2 文件上傳核心在於 FileUploadInterceptor 自動綁定 File、contentType、fileName 三屬性。結合伺服器端驗證框架與 JavaScript 客戶端預檢,可構建安全、友善的上傳體驗。生產環境建議加入檔案內容檢測、病毒掃描與雲端儲存整合。