2012-12-20 46 views
0

我想使用S:file標籤上傳文件,但它給了我http 500內部錯誤。但是當我直接在相同的代碼中將文件名和路徑作爲常量運行時。所以我不確定我在哪裏丟失了循環漏洞。使用s:struts2文件上傳:文件

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1"%> 
<%@ taglib prefix="s" uri="/struts-tags"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<title>Struts 2 - Login Application | ViralPatel.net</title> 
</head> 

<body> 
<h2>Struts 2 - Login Application</h2> 
<s:actionerror /> 
<s:form action="uploadFile.action" method="post" enctype="multipart/form-data" > 
<s:textfield name="myName"></s:textfield> 
    <s:file name="myFile"></s:file> 
    <s:submit value="Submit" align="center" /> 
</s:form> 
</body> 
</html> 

行動

class FileUploadAction extends ActionSupport implements ServletRequestAware { 
    File userImage; 
    String userImageContentType; 
    String userImageFileName; 
    HttpServletRequest servletRequest; 

    public String execute() { 
     try { 
      String filePath = servletRequest.getSession() 
        .getServletContext().getRealPath("/"); 
      File fileToCreate = new File(filePath, this.userImageFileName); 
      FileUtils.copyFile(this.userImage, fileToCreate); 
     } catch (Exception e) { 
      addActionError(e.getMessage()); 
      return INPUT; 
     } 
     return SUCCESS; 
    } 

    public void setServletRequest(HttpServletRequest servletRequest) { 
     servletRequest = servletRequest; 
    } 
} 

配置

<action name="userImage" class="net.viralpatel.struts2.FileUploadAction"> 
    <interceptor-ref name="fileUpload"> 
     <param name="maximumSize">2097152</param> 
     <param name="allowedTypes"> 
        image/png,image/gif,image/jpeg,image/pjpeg 
      </param> 
    </interceptor-ref> 
    <interceptor-ref name="defaultStack"> 
    </interceptor-ref> 
    <result name="success">SuccessUserImage.jsp</result> 
    <result name="input">UserImage.jsp</result> 
</action> 

編輯:下一次編輯您的帖子,而不是張貼在留言代碼...

+0

請發佈您的'UploadFile'動作。 – Atropo

+0

你會得到什麼例外? –

回答

1

編輯: 您的Action沒有使用其GETTER的private File myFile;

開始糾正...


這個問題可能是在你的動作代碼,而不是在這裏。

如果傳遞包含文件名/路徑的字符串,它是什麼意思?

你有一個private File myFile;與行動(和文件是java.io.File,而不是其他文件)的公共訪問器(getter和setters)?

看看這兩個簡單的教程太:

http://viralpatel.net/blogs/struts-2-file-upload-save-tutorial-with-example/

http://www.roseindia.net/struts/struts2/struts-2-file-upload.shtml

+1

這可能比答案更多評論。 –

+0

是的,但相當長的評論:/ –

+0

當我在我的jsp文件中使用enctype =「multipart/form-data」時,我得到HTTP 500內部錯誤,當我不使用它時,得到HTTP 404未找到異常。 – user1917911

0

你把fileUpload攔截兩次,你的行動攔截器棧,因爲defaultStack已經包含fileUpload攔截。您可以配置內部堆棧攔截這樣的:

<action ...> 
    <interceptor-ref name="defaultStack"> 
    <param name="fileUpload.allowedTypes"> 
     image/png,image/gif,image/jpeg,image/pjpeg 
    </param> 
    </interceptor-ref> 
    <result ... /> 
</action> 

還要確保您有公共的getter/setter方法action類裏面的變量。