gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:03:56 25 4
gpt4 key购买 nike

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

到目前为止,我已经能够在用户特定路径中上传文件,并详细讨论如何在网页中显示它。

我正在关注mkyong但我在这里发现的问题是操作结果在流中,而在我的情况下,值堆栈有其他操作详细信息。

代码片段:

1. Action 类

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>

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

最佳答案

您不能同时返回 JSP 页面二进制文件。

返回 JSP 时,使用 dispatcher结果,返回文件时,使用 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".

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

关于java - 如何上传文件(txt,pdf)并在同一网页中显示它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35271586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com