基本原理?
必须要把表单上传的数据的编码方式转为二进制数据。
表单的enctype = multipart/form-data.
上传框架?
1、Common-FileUpload
2、O'Reilly的COS
用Common-FileUpload(Struts2默认的上传框架)
会用到的包Common-FileUpload.jar和Common-IO.jar
封装了很多东西,已经很简单了。
注意Action中命名规则,文件类型***ContentType,文件名***FileName,页面通过setter与getter自动赋值。
直接从输出流中读取数据到输入流就完成了上传功能了,Servlet则要更复杂
package cn.guet.hj.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
*
* 用Common-upload上传文件的Action
*
*/
public class UploadAction extends ActionSupport{
//上传文件的标题
private String title;
private File upFile;//上传文件
private String upFileContentType;//文件类型
private String upFileFileName;//文件名
private String savePath;//保存路径
public String getUpFileContentType() {
return upFileContentType;
}
public void setUpFileContentType(String upFileContentType) {
this.upFileContentType = upFileContentType;
}
public String getUpFileFileName() {
return upFileFileName;
}
public void setUpFileFileName(String upFileFileName) {
this.upFileFileName = upFileFileName;
}
public String getSavePath() {
//取得Request对象
HttpServletRequest request = ServletActionContext.getRequest();
//取得应用的真实目录 作为保存目录
return request.getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String execute()throws Exception{
this.setSavePath("WEB-INF/uploadfile");
//输出流
FileOutputStream fos = new FileOutputStream(this.getSavePath()+File.separator+this.getUpFileFileName());
//输入流
FileInputStream fis = new FileInputStream(this.getUpFile());
//一次读写 读到内存
int length = (int)this.getUpFile().length();
byte[] buff = new byte[length];
fis.read(buff);
fos.write(buff);
//边读边写的方式
// int len = 0;
// while((len=fis.read())!=-1){
// fos.write(len);
// }
fis.close();
fos.close();
return SUCCESS;
}
……
}
要注意的是:读写方式
1、一次读到内存再一次写到文件中,好处,方便速度快。
//一次读写 读到内存
int length = (int)this.getUpFile().length();
byte[] buff = new byte[length];
fis.read(buff);
fos.write(buff);
2、边读边写
//边读边写的方式
int len = 0;
while((len=fis.read())!=-1){
fos.write(len);
}