struts实现单文件上传

来源:互联网 发布:绑定网卡linux 6.5 编辑:程序博客网 时间:2024/05/22 06:34

1.定义一个用于文件上传的jsp页面


2.配置struts.xml


3.定义后台类

public class upload implements Action{    private File  upload;    private String uploadContentType;    private  String uploadFileName;    private  String savePath;    public File getUpload() {        return upload;    }    public void setUpload(File upload) {        this.upload = upload;    }    public String getUploadContentType() {        return uploadContentType;    }    public void setUploadContentType(String uploadContentType) {        this.uploadContentType = uploadContentType;    }    public String getUploadFileName() {        return uploadFileName;    }    public void setUploadFileName(String uploadFileName) {        this.uploadFileName = uploadFileName;    }    public String getSavePath() {        return ServletActionContext.getServletContext().getRealPath(savePath);    }    public void setSavePath(String savePath) {        this.savePath = savePath;    }    public String execute() throws Exception {        byte[]  bytes=new byte[1024];        FileInputStream  fileInputStream=new FileInputStream(getUpload());        FileOutputStream  fileOutputStream=new FileOutputStream(getSavePath()+"//"+getUploadFileName());        int read = fileInputStream.read(bytes);        while (read>0){            fileOutputStream.write(bytes,0,read);            read=fileInputStream.read(bytes);        }        fileOutputStream.flush();        fileOutputStream.close();        fileInputStream.close();        return SUCCESS;    }}