如何上传一个文件(txt,pdf)并在同一个网页上显示?

How to upload a file(txt,pdf) and show it in the same webpage?

我正在编写一个逻辑,当用户第一次访问该网页时(例如,在他的个人资料页面中),用户上传一个文本文件。下次当用户访问该网页时,他应该能够找到上传的文件 link.

到目前为止,我已经能够将文件上传到用户特定的路径,并专注于如何在网页中显示它。

我正在关注 mkyong,但我发现这里的问题是操作结果在流中,而在我的情况下,valuestack 有其他操作细节。

代码片段:

1.动作Class

public String uploadResume(){

    try{

        if(uploadFile==null){
            throw new NullPointerException();
        }

    File file = new File("/Users/shibasish/Documents/","/" 
                    + GenerateTimestampID.generateTimestamp()+"/shibasish");
    if (!file.exists()) {
        if (file.mkdirs()) {
            System.out.println("Directory is created!");
        } else {
            System.out.println("Failed to create directory!");
        }
    }
    String filePath = file.getPath();
    File fileToCreate = new File(filePath, uploadFileFileName);
    FileUtils.copyFile(uploadFile, fileToCreate);       

    }catch(NullPointerException e){
        addActionError("Please upload a resume");
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return "success";
}

2.struts.xml

<action name="uploadResume" class="com.msventure.web.actions.CompleteProfileAction" 
              method="uploadResume"> 
    <interceptor-ref name="defaultStack">
    <param name="fileUpload.allowedTypes">
        text/plain,application/pdf,application/octet-stream
    </param>
</interceptor-ref> 
        <result name="success">/profile.jsp</result>
        <result name="fail">/login.jsp</result>
        <result name="index">/index.jsp</result>
          <result name="login">/talent.jsp</result>
    </action>

JSP

<form id="login" name="login" method="post" action="signup">
<p>
    <input type="submit" value="Update" />
</p>
  </form> 

  <s:if test="uploadFile neq null">
  <!--<h4>Download file - <s:a href="uploadFile">fileABC.txt</s:a></h4>-->
  <a href="<s:property value="uploadFile" />" />
  </s:if>
  <s:form id="login" name="login" method="post" action="uploadResume" 
       enctype="multipart/form-data">
    <s:file name="uploadFile" label="Select a File to upload" size="40"/>
    <s:submit value="submit" name="submit"/>
    <!--<input type="button" value="Search" id="resumeupload" />-->
</s:form>

如果我不清楚,请告诉我。

您不能return既是JSP页面又是二进制文件。

当 returning JSP 时,使用 dispatcher 结果,当 returning 文件时,使用 stream 结果。

上传文件后,您有两个选择:

1. Show only the file

post the form in a new tab with target="_blank" and return a stream result; the user will end up having two tabs, one with the profile, the other with the document.

2. Show a JSP with the file embedded in it

Use an <iframe> in the profile page, and post the form targeting the iframe, with target="name_of_the_frame_here".

还有更复杂的方法(returning a JSP,并在服务器端编写一个 id,您将在 iframe 调用的辅助操作中使用该 id 来获取文档),但我只是选择解决方案 #2.

尽管 Andrea 提供了可能的最佳方法,但我正在上传我使用 iframe 使用的代码,并在重新登录时下载用户特定的文件。 希望对您有所帮助。

1.JSP : 这是 iframe

里面的 JSP
<s:form id="login" name="login" method="post" action="uploadResume" 
                                             enctype="multipart/form-data">
    <s:file name="uploadFile" label="Select a File to upload" size="40"/>
    <s:submit value="submit" name="submit"/>
</s:form><a href="downloadResume">Download file</a>

2.Action 方法: 上传简历后,坚持用户特定 path.I 已使用 cookie 进行用户识别。

public String downloadResume() {

    try {

        Cookie[] currentCookie;
        String usrCookie = "sample";
        String cookieFlg;
        currentCookie = request.getCookies();

        for (int i = 0; i < currentCookie.length; i++) {
            if (currentCookie[i].getName().equals("_usr")) {
                usrCookie = currentCookie[i].getValue();
            }
        }

        if (!usrCookie.equalsIgnoreCase("sample")) {

            userProfileObj = new UserProfile();

            String pathloc=userProfileObj.getResumePath(usrCookie);

            if(pathloc==null){
                //throw new NullPointerException();
                addActionError("Please upload a resume");
                return "fail";
            }
            else{
            File folder = new File(pathloc);
            File[] listFile=folder.listFiles();
            File fileToDownload=new File(pathloc+"/"+listFile[1].getName());
            for(int i=0;i<listFile.length;i++){
                System.out.println("list of files : "+listFile[i].getName());
            }
            //System.out.print("Files in the directory : "+fileToDownload);

            inputStream = new FileInputStream(fileToDownload);
            fileName = fileToDownload.getName();
            Long contentLength = fileToDownload.length();
            }
        }

    } catch (NullPointerException e) {
        e.printStackTrace();
        addActionError("Please upload a resume");
        return "success";
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "success";
}

3.struts.xml

<action name="downloadResume" class="com.msventure.web.actions.CompleteProfileAction" 
                             method="downloadResume">
        <result name="success" type="stream">
            <param name="contentType">application/octet-stream</param>
            <param name="inputName">inputStream</param>
            <param name="contentDisposition">attachment;filename="${fileName}"</param>
            <param name="bufferSize">1024</param>
        </result>
        <result name="fail">/filemanagement.jsp</result>
    </action>