1.提交方式必须是post
2.表单中的上传项必须有name属性
3.表单的 enctype 属性必须是multipart/form-data
Action中:
//文件上传需要的参数
private File upload;//上传的文件
private String uploadFileName; //接收文件名
private String uploadContextType;//接收文件类型
public void setUpload(File upload) {
this.upload = upload;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setUploadContextType(String uploadContextType) {
this.uploadContextType = uploadContextType;
}
public void setCategorySecondService(CategorySecondService categorySecondService) {
this.categorySecondService = categorySecondService;
}
public String save() {
product.setPdate(new Date());
if(upload != null) {
//获得文件上传的磁盘绝对路劲
String realPath = ServletActionContext.getServletContext().getRealPath("/products");
//创建一个文件
File disFile = new File(realPath+"//"+uploadFileName);
//文件上传
try {
FileUtils.copyFile(upload, disFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
product.setImage("products/"+uploadFileName);
}
//将数据保存到数据库
productService.save(product);
return "savesuccess";
}
jsp代码:
<tr>
<td width="18%" align="center" class="ta_01" bgColor="#ffffff">
商品图片:
</td>
<td class="ta_01" bgColor="#ffffff">
<input type="file" name="upload"/>
</td>
</tr>