- 要想使用 HTML 表单上传一个或多个文件
- 须把 HTML 表单的
enctype
属性设置为multipart/form-data
- 须把 HTML 表单的
method
属性设置为post
- 需添加
<input type=“file” name="upload">
字段. - 在对应的action中创建同名变量
upload
来接受jsp传来的file
实例 :
添加商品的时候要上传商品的图片
<form id="fileForm" name="Form1" action="${pageContext.request.contextPath}/product_save.action" method="post" enctype="multipart/form-data">
<!-- 文件上传 -->
<input type="file" name="upload" />
</form>
对应的action中
/**
* 保存新添加的商品
* @return
*/
//上传文件需要的三个属性
private File upload; //上传的文件对象
private String uploadFileName;//文件名
private String uploadContentType;//文件的MIME值,即文件类型
public void setUpload(File upload) {
this.upload = upload;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
//保存添加的商品
public String save() throws IOException{
/**
* 处理上传文件
*/
//1.获得上传文件的一个输入流
InputStream is = new FileInputStream(upload);
//2.获得要上传文件到那个目录的绝对路径
String root = ServletActionContext.getServletContext().getRealPath("/products");
//3.创建一个文件用来接受上传的文件
File toFile = new File(root+"//"+uploadFileName);
// 4. 创建toFile的输出流
OutputStream os = new FileOutputStream(toFile);
//5. 拷贝文件upload到toFile
int len=0;
byte[] buff = new byte[1024];
while((len=is.read(buff,0,buff.length)) != -1){
os.write(buff, 0, len);
}
//6.关闭流
os.close();
is.close();
product.setImage("products/"+uploadFileName);
product.setPdate(new Date());//设置商品创建时间
productService.save(product);
return "save";
}
完了之后配置好struts2的xml文件,即刻提交文件并上传到指定的文件夹目录下