Struts2之通过commons-fileupload实现文件上传

先引入包commons-fileupload-1.2.jar 或者更高版本

commons-io-1.3.1.jar

在webRoot目录下建立upload文件夹      这是重点不然,要报错,系统找不到路径

 

 

 

upload.jsp

<%@ page language="java" contentType="text/html; charset=GBK"%>
<%@taglib prefix="s" uri="/struts-tags"%>



修改默认的提示信息







    文件标题:

    选择文件:

   


succ.jsp

<%@ page language="java" contentType="text/html; charset=GBK"%>
<%@taglib prefix="s" uri="/struts-tags"%>

   
        上传成功
   
   
        上传成功!

        文件标题:

        文件为:"/>

   

web.xml

   
   
        struts2
        org.apache.struts2.dispatcher.FilterDispatcher
   

   
   
        struts2
        /*
   

struts.xml


   
   
   
       
             
                image/bmp,image/png,image/gif,image/jpeg 
                20000 
           
 
               
                     
            /upload
            /upload.jsp 
            /succ.jsp  
       

   

 

 


建立globalMessages.properties

struts.messages.error.content.type.not.allowed=您上传的文件类型只能是图片文件!请重新选择!
struts.messages.error.file.too.large=您要上传的文件太大,请重新选择!

建立globalMessages_zh_CN.properties

 

通过native2ascii     路径/globalMessages.properties   路径/globalMessages_zh_CN.properties

编译为字符代码


UploadAction.java

public class UploadAction extends ActionSupport {
    private String title;
    private File upload;
    private String uploadContentType;
    private String uploadFileName;

    // 接受依赖注入的属性
    private String savePath;

    // 接受依赖注入的方法
    public void setSavePath(String value) {
        this.savePath = value;
    }
    private String getSavePath() throws Exception {
        return ServletActionContext.getRequest().getRealPath(savePath);
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public void setUpload(File upload) {
        this.upload = upload;
    }
    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }
    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
    public String getTitle() {
        return (this.title);
    }
    public File getUpload() {
        return (this.upload);
    }
    public String getUploadContentType() {
        return (this.uploadContentType);
    }
    public String getUploadFileName() {
        return (this.uploadFileName);
    }
    @Override
    public String execute() throws Exception {
        // 以服务器的文件保存地址和原文件名建立上传文件输出流
        FileOutputStream fos = new FileOutputStream(getSavePath() + "//"+ getUploadFileName());
        FileInputStream fis = new FileInputStream(getUpload());
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        return SUCCESS;
    }
}

 

你可能感兴趣的:(Struts)