无法使用struts2显示上传的图像

时间:2014-09-15 04:39:38

标签: jsp struts2

我正在尝试将图像上传到mySQL数据库,并使用struts2标记将其显示在jsp上。我可以将图像上传到服务器但无法在jsp中显示。我在互联网上搜索并做了所有我可以做的改变。我仍然无法在jsp上显示图像,这让我怀疑图像是否上传。请仔细检查我的代码并告诉我我在哪里做错了。三江源。

这是我的jsp。

<%@ taglib prefix="s" uri="/struts-tags"%> 
<div id="form_container" align="center">
    <s:form action="upload" method="post" enctype="multipart/form-data">
        .
        .
        <s:file         name="image"                    label="Retinal Image"/>
        <s:submit       value="upload"/>
    </s:form>
</div>

动作类。

String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
System.out.println("Server path:" + filePath);
File fileToCreate = new File(filePath, uploadBean.getImageFileName());

System.out.println("fileToCreate="+fileToCreate.getName());
FileUtils.copyFile(uploadBean.getImage(), fileToCreate);
Map session     = ActionContext.getContext().getSession();      
session.put("image",filePath);
//some code for keeping image in database which is showing as success as I can see blob in the table after this code was run

UploadBean.java

private File    image;
private String  imageContentType;
private String  imageFileName;
//getters and setters

最后,此图片必须显示在成功页面中。 Uploaded.jsp

<s:property value="imageFileName"/>
<s:property value="imageContentType"/>
<s:property value="image"/>
<img src="#session.image"/>

我的struts.xml是

<action name="upload"       class="com.ActionClasses.UploadAction">
    <interceptor-ref name="fileUpload">
        <param name="maximumSize">3145728</param>
        <param name="allowedTypes">image/png,image/gif,image/jpeg,image/pjpeg, image/jpg</param>
    </interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>
    <result name="success"  type="tiles">   uploaded    </result>
    <result name="error"    type="tiles">   upload      </result>
    <result name="input"    type="tiles">   upload      </result>
</action>

请告诉我我做的错误。 Thankou。

1 个答案:

答案 0 :(得分:0)

图像路径应该是相对路径.ie relativePath \ + filename.ext

string  imageRelPath=<relativePath>+"\\"+uploadBean.getImageFileName()

session.put("image"imageRelPath)

示例:假设您已将文件abc.jpg上传到图像文件夹

String filePath = servletRequest.getSession()。getServletContext()。getRealPath(“/”);

filePath=filePath+"\\"image;

然后你的“imageRelPath”将是

imageRelPath="./image/abc.jpg"

在你的情况下它会

imageRelPath="./abc.jpg" i.e 

session.put("image","./"+uploadBean.getImageFileName());

因为您没有存储在任何子文件夹