簡體   English   中英

使用struts2在網絡應用程序中上傳和下載文件

[英]File upload and Download in a web app using struts2

在struts2上載方法中,我可以選擇上載文件的保存位置。 我的意思是,Web中的所有示例都要求我將其存儲在WEB-INF中,這肯定不是一個好主意。 我希望能夠將上傳的文件存儲在磁盤上的任何位置。

我該怎么辦? 我可以借助ServletContextAware攔截器嗎?

當我使用

public class DownloadFileAction extends ActionSupport implements ServletContextAware{
    //private InputStream inputStream;
    private int fileid;
    private ServletContext servletContext;
    private FileCrud fileCrud;
    private MyFile myFile;

    public FileCrud getFileCrud() {
        return fileCrud;
    }
    public void setFileCrud(FileCrud fileCrud) {
        this.fileCrud = fileCrud;
    }
    public MyFile getMyFile() {
        return myFile;
    }
    public void setMyFile(MyFile myFile) {
        this.myFile = myFile;
    }
    public InputStream getInputStream(){

        String homepath = "c:\\files";
        String fname = null;
        try{
            fname=getFileCrud().getAFileName(getFileid());
        }catch(Exception e){
            e.printStackTrace();
        }
        String thePathToFile = homepath+File.separator+fname;
        //File targetfile = new File(thePathToFile);

        return getServletContext().getResourceAsStream(thePathToFile);
    }
//  public void setInputStream(InputStream inputStream) {
//      this.inputStream = inputStream;
//  }
    public int getFileid() {
        return fileid;
    }
    public void setFileid(int fileid) {
        this.fileid = fileid;
    }
    public ServletContext getServletContext() {
        return servletContext;
    }
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
    public String execute(){
        return SUCCESS;
    }

}

和struts xml文件是

<action name="fileDownload" class="com.projit1.file.DownloadFileAction">
            <result type="stream" name="success">
                <param name="inputName">inputStream</param>
                <param name="contentType">application/octet-stream</param>

            </result>
        </action>

我收到以下錯誤

javax.servlet.ServletException: java.lang.IllegalArgumentException: Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name="inputName"> tag specified for this action.
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)

我正在嘗試,但未得到任何結果。

要將InputStream寫入File ,需要FileOutputStream

要從File獲取InputStream ,需要FileInputStream

在您的代碼中,您嘗試使用ServletContext#getResourceAsStream()分配文件,但這旨在分配類路徑資源。 new FileInputStream(file)替換它。

剛剛自己完成此操作。 我建議分別解決這兩個問題。 先上傳文件,然后下載文件。 下載支持的一個直接問題是,您的結果配置沒有public getInputStream()方法:

<param name="inputName">inputStream</param>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM