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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值