简体   繁体   中英

struts2 file upload success message on same page using ajax

我正在上载.csv文件并在同一页面上重定向,我想在同一页面上将显示文件成功上载消息。我不想使用ajax发送请求。我对struts框架是陌生的文件上传教程,但每个人都重定向到另一个页面并在其中显示消息。

After the upload (and in case of errors), dispatch the same page you come from:

Struts.xml

    <action name="uploadPage" class="foo.bar.UploadAction">
        <result>/upload.jsp</result>
        <result name="input">/upload.jsp</result>
        <result name="error">/upload.jsp</result>
    </action>
    <action name="doUpload"   class="foo.bar.UploadAction" method="upload">
        <result>/upload.jsp</result>
        <result name="input">/upload.jsp</result>
        <result name="error">/upload.jsp</result>
    </action>

UploadAction

    public class UploadAction extends ActionSupport {       
        File   upload;
        String uploadFileName;
        String uploadContentType;       
        /* Getters and Setters for the above properties */

        public String execute() {
            return SUCCESS;
        }

        public String upload(){             
            try {
                getService().upload(upload,uploadFileName,uploadContentType);
                addActionMessage("Upload successfully completed");
                return SUCCESS;
            } catch (Exception e){
                addActionError("Error while uploading: " + e.getMessage());
                return ERROR;
            }
        }
    }

upload.jsp

<body>
    <s:if test="hasActionErrors()">
        <s:actionerror />
    </s:if>
    <s:if test="hasActionMessages()">
        <s:actionmessage />    
    </s:if>

    <s:form action="doUpload" enctype="multipart/form-data">
        <s:file name="upload" />
        <s:submit />
    <s:form>
</body>

This is basic, then you may want to alter the URL or use Post Redirect Get or Tokens etc.. to prevent the user to resubmit the file when refreshing.

set ActionError in your action(if file doesnt meet your criteria) using

     addActionError("file not uploaded something went wrong");

otherwise set action message

     addActionMessage("Upload successfully completed");

jsp page.

<body>
    <s:actionerror />
    <s:actionmessage />    

 <s:form action="uploadAction" >
    <s:file name="filename" /> 
    <s:submit />
 <s:form>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM