struts2传文件时出现错误及解决和显示方法

来源:互联网 发布:双色球中奖计算器算法 编辑:程序博客网 时间:2024/06/05 07:50

1.报这种HTTP Struts 500的错误

   这是因为你tomcat所部署的工程目录下没有装图片的那个文件夹,所以最好手动新建一个。

2.也是我遇到最坑爹的错误。

      一定要确保这几个set方法中,前面和文件是相同的。也就是setDoc,setDocFileName,setDoContentType.反正我就是这里卡住了,调试了好久。虽然还没搞清楚为什么是这样,但是应该改成一样的才能证明这几个有点联系吧。
    
   

3.关于如何在页面显示

       其实我是先用一个页面传图片,然后再到另一个页面将其显示出来,这样直接用session或request可以调用。下面是核心代码展示:
public String execute() throws Exception{String targetFileName = new Date().getTime() + fileName;System.out.println(fileName);//String targetFileName = generateFileName(fileName);System.out.println(targetFileName);String targetDirectory = ServletActionContext.getServletContext().getRealPath("/pic/" + targetFileName);//文件最终所在的路径//在指定目录创建文件//File target = new File(targetDirectory,targetFileName);//把要上传的文件copy过去//FileUtils.copyFile(doc, target);FileOutputStream out = new FileOutputStream(targetDirectory);FileInputStream in = new FileInputStream(doc);byte[] buffer = new byte[1024];int len = 0;while((len=in.read(buffer))!=-1){out.write(buffer,0,len);}out.close();in.close();session.put("filePath", "pic/" + targetFileName);return "success";}

配置struts及spring
<action name="product_pic" class="productPicAction"><result type="redirect" name="success">AddProduct.jsp</result></action>

  <bean id="productPicAction" class="com.ssh.action.ProductPicAction" scope="prototype">     </bean>


展示图片的页面
 <s:form action="product_save" method="post" namespace="/" theme="simple">  <table border="1" width="350px">  <tr>  <td>商品图片</td>  <td><img width="150px" height="150px" alt="" src="${sessionScope.filePath}"></td>  </tr>  <tr>  <td>商品名称</td>  <td><s:textfield name="pname"></s:textfield></td>  </tr>  <tr>  <td>商品价格</td>  <td><s:textfield name="price"></s:textfield></td>  </tr>    <tr>  <td colspan="2"><input type="submit" value="添加"></td>  </tr>  </table>  </s:form>



注**:这是本人第一次写博客哦,希望对大家有用,也希望以后有更多的经验和大家分享。

1 0
原创粉丝点击