struts 文件上传

jsp页面:
<html:form action="/product.do?method=addProduct" enctype="multipart/form-data" >
//……
图片:<html:file property="value(file)" styleId="file"/>
<input type="submit" name="Submit" value="提交" />
</html:form>

ProductAction:
public ActionForward addProduct(ActionMappingmapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
PublicForm pubform = (PublicForm) form;
Productinfo product = new Productinfo();
//……
String encoding = request.getCharacterEncoding();
FormFile thefile;
if (encoding != null && encoding.equalsIgnoreCase("utf-8")) {
response.setContentType("text/html; charset=gb2312");
}
try {
thefile =(FormFile)pubform.getValue("file");//取得上传文件
if (!thefile.getFileName().equals("")) {
String filepath = this.getServlet().getServletContext().getRealPath("/"); // 获取当前系统路径
OutputStream ops = new FileOutputStream(filepath+ "productImg\\" + thefile.getFileName()); // 构建一个上传文件的输出流
ops.write(thefile.getFileData()); //可以直接写进去
ops.close();
String imgpath = thefile.getFileName();
product.setImgpath(imgpath);
} else {
String imgpath = null;
product.setImgpath(imgpath);
}
} catch (Exception ex) {
ex.printStackTrace();
}
我是只保存一个文件名到到数据库 以后在获取的时候前面先加上路径
其中的PubliForm 是我的一个公用的Form
public class PublicForm extends ActionForm {

protected Map map = new HashMap();

public void setValue(String key, Object value) {
map.put(key, value);
}

public Object getValue(String key) {
return map.get(key);
}

public Map getMap() {
return map;
}

public void reset(ActionMapping mapping, HttpServletRequest req) {
map.clear();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值