struts实现单文件上传

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

struts实现单文件上传_第1张图片

2.配置struts.xml

struts实现单文件上传_第2张图片

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;
    }
}

你可能感兴趣的:(struts实现单文件上传)