Struts2的一个和多个文件上传的实现

在Struts2中,上传文件时,只要使用java.io.File类来描述上传文件即可,比直接使用Commons-FileUpload组件要简单的多。

上传单个文件:

如果上传的是单个文件,则在Action类中定义一个File类型的变量。该变量的名字与JSP页面上的标签的name属性相对应,只有这样Struts2才能使客户端上传的文件自动与Action类中的相应的属性进行关联处理。

上传多个文件:

如果上传的是多个文件,这时在JSP页面中的所有的标签的name属性值都必须相同,这时Action中相对应的属性就要使用List或File[]用来表示多个文件的信息。

保存文件相关属性的变量设置如下:

private List upload; //保存上传的文件
private List uploadContentType; //保存上传的文件类型
private List uploadFileName; //保存上传的文件名

以下是一个使用Struts 2上传多个文件的例子,把上传的文件重新用生成的随机数命名:

Struts2上传文件相关代码

public class UploadFilesAction extends ActionSupport {

private List upload;
private List uploadContentType;
private List uploadFileName;
private String uploadPath;
private String result;
private boolean success;
private String msg;
public boolean isSuccess() {
    return success;
}
public String getMsg() {
    return msg;
}
public String getResult() {
    return result;
}
public void setUpload(List upload) {
    this.upload = upload;
}
public void setUploadContentType(List uploadContentType) {
    this.uploadContentType = uploadContentType;
}
public void setUploadFileName(List uploadFileName) {
    this.uploadFileName = uploadFileName;
}
public void setUploadPath(String uploadPath) {
    this.uploadPath = uploadPath;
}
public String execute() throws Exception {
    for (int i = 0; i < uploadFileName.size(); i++) {
                    Random random = new Random();
                    String filename = uploadFileName.get(i);                         
                    //把上传的文件用生成的随机数重新命名
                    //并判断生成的文件名是否已经存在
                    //如果存在,则继续生成随机数命名,直到找打还没使用的随机数为止
                    filename = uploadPath + random.nextLong()
                            \+ filename.substring(filename.lastIndexOf("."));
                    while (new File(filename).exists()) {
                        filename = uploadPath + random.nextLong()
                                \+ filename.substring(filename.lastIndexOf("."));
                    }
                    FileOutputStream fos = new FileOutputStream(filename);
                    InputStream is = new FileInputStream(upload.get(i));
                    byte\[\] buffer = new byte\[8192\];
                    int count = 0;
                    while ((count = is.read(buffer)) > 0) {
                        fos.write(buffer, 0, count);
        }
        fos.close();
        is.close();
    }
    success=true;
    msg = "文件上传成功!";
    return "result";
}

}

在struts.xml文件中可做如下配置:



/WEB-INF/result.jsp
D:\UploadFiles\

arthinking wechat
欢迎关注itzhai公众号