1.
单文件上传
上传文件对表单的要求:
1. 表单要使用post方式提交
2. 表单的enctype是multipart/form-data
3. 表单中要有file类型的input文本域
Struts上传也是基于拦截器,底层还是使用commons-fileupload组件
Struts上传的步骤
(1) 建立表单
<form action="${pageContext.request.contextPath }/upload/renliang" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="username"><br>
文件:<input type="file" name="upload"><br>
<input type="submit">
</form>
(2)创建Action
注意:
接收的文件属性:和表单中文本域file类型input的name一致
接收的文件名字:file的name+FileName固定写法[固定写法,应该是表单中File类型的input的name属性值+FileName]
接收的文件MIME类型:file的name+ContentType[固定写法,应该是表单中File类型的input的name属性值+ContextType;]
action代码:
public class UploadAction extends ActionSupport{
private String username;
/**
* 要接收的文件,命名需要和表单中的file类型的input的name一致
*/
private File upload;
/**
* 文件名的接收 File属性名FileName:固定写法
*/
private String uploadFileName;
/**
* 获得上传文件的MIME类型,File属性名字ContentType:固定写法
*/
private String uploadContentType;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String upload() throws Exception{
//获得servletContext
ServletContext sc = ServletActionContext.getServletContext();
//获得服务的绝对路径
String realPath = sc.getRealPath("/");
realPath = realPath + "upload\\"+uploadFileName;
//定义输入输出流
InputStream in = new FileInputStream(upload);
OutputStream out = new FileOutputStream(realPath);
int len = -1;
byte[] bs = new byte[1024];
while((len = in.read(bs)) != -1){
out.write(bs, 0, len);
}
out.close();
in.close();
return super.SUCCESS;
}
}
利用工具类可以减少一些代码:
利用工具类就是一行代码,却替换掉了inputstream,outputstream写入写出以及关闭等等之类的代码
InputStream in = new FileInputStream(upload);
OutputStream out = new FileOutputStream(realPath);
int len = -1;
byte [] bs = new byte[1024];
while((len = in.read(bs) ) != -1 ){
out.write(bs, 0, len);
}
out.close();
in.close();
/*
* 利用文件工具类来减少代码
*/
FileUtils.copyFile(upload, new File(realPath));