Struts2 拦截器自動將上傳文件封裝為 File 屬性,並注入 fileName、contentType。
public class UploadAction extends ActionSupport {
private File image;
private String imageFileName;
private String imageContentType;
public String execute() {
String realPath = ServletActionContext.getServletContext().getRealPath("/images");
if (image != null) {
File dest = new File(new File(realPath), imageFileName);
FileUtils.copyFile(image, dest); // commons-io
ActionContext.getContext().put("message", "上傳成功");
}
return SUCCESS;
}
// getter/setter 省略
}
public class UploadAction2 extends ActionSupport {
private File image;
private String imageFileName;
private String imageContentType;
private String savePath; // struts.xml 注入
@Override
public String execute() {
try (FileOutputStream fos = new FileOutputStream(getSavePath() + "/" + imageFileName);
FileInputStream fis = new FileInputStream(image)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) fos.write(buffer, 0, len);
} catch (Exception e) { e.printStackTrace(); return ERROR; }
return SUCCESS;
}
public String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
// getter/setter 省略
}
<constant name="struts.multipart.maxSize" value="10701096"/> <!-- 10MB -->
<constant name="struts.multipart.saveDir" value="d:/tmp"/>
<package name="upload2" extends="struts-default">
<action name="upload2" class="com.ljq.action.UploadAction2">
<param name="savePath">/images</param>
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
<param name="maximumSize">1025956</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
<result name="success">/WEB-INF/page/message.jsp</result>
<result name="input">/upload/upload.jsp</result>
</action>
</package>
<form action="${pageContext.request.contextPath}/upload2/upload2.do"
enctype="multipart/form-data" method="post">
文件: <input type="file" name="image">
<input type="submit" value="上傳">
</form>
| 維度 | 方式一 | 方式二 |
|---|---|---|
| 代碼簡潔度 | 高(依賴 commons-io) | 低(手動流控制) |
| 靈活性 | 固定保存邏輯 | 可控制緩衝區、斷點續傳擴展 |
| 異常處理 | 框架統一 | 需自行捕獲 |
| 推薦場景 | 常規業務上傳 | 特殊存儲邏輯、大文件分片 |