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

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

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 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 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();
}



}

}

}
}

你可能感兴趣的:(commons-fileupload-1.2.2.jar包的上传图片的使用)