commons-fileupload-1.2.2.jar包的上传图片的使用

<form id="productAdd" action="ProductServlet?poperate=addProduct" method="post" enctype="multipart/form-data">

//解析表单中所有的文件

String p_name = null;
String p_description = null;
String pc_child_id_s = null;
String p_price_s = null;
String p_stock_s = null;
String p_path = "/Shopping/images/product";
String fname = null;


try {
List<FileItem> list = sfu.parseRequest(request);

System.out.println("绝对路径:"+request.getContextPath());
for (FileItem item : list) {
if(item.isFormField()){

System.out.println("表单项名称:" + item.getFieldName());
//判断字段名,并获得各个表单项的值
if("productName".equals(item.getFieldName())){
p_name = item.getString("utf-8");
}else if("productDetail".equals(item.getFieldName())){
p_description = item.getString("utf-8");
}else if("childId".equals(item.getFieldName())){
pc_child_id_s = item.getString("utf-8");
}else if("productPrice".equals(item.getFieldName())){
p_price_s = item.getString("utf-8");
}else if("productNumber".equals(item.getFieldName())){
p_stock_s = item.getString("utf-8");
}

}else{//文件表单字段,获取上传文件的名字
if(item.getFieldName() != null){
//保存此文件并输出保存成功
String filename = item.getName();
System.out.println(filename);

File sourceFile = new File(filename);
//上传文件的名字
fname = sourceFile.getName();
System.out.println("上传文件的名字:"+filename);
List<String> exts = Arrays.asList("jpg","gif","png");

String ext = fname.substring(fname.lastIndexOf('.')+1);

if(exts.contains(ext)){
String path = this.getServletContext().getRealPath("/") + "images\\product";
//String path = "E:/workee/.metadata/.plugins/org.eclipse.wst.server.core/tmp3/wtpwebapps/Shopping/images/product";
//String path = "C:/Users/Administrator/git/Shopping/WebContent/images/product";
//String path = "C:/Users/Administrator/git/Shopping/images/product";
//path = this.getServletContext().getRealPath("/imagesOfProduct");
File savefile = new File(path,fname);

try {
item.write(savefile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}

}

}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值