package com.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.common.base.BaseAction;
import com.common.util.Configuration;
import com.common.util.FileExtensionHelper;
import com.common.util.StringUtils;
import com.entity.FileBag;
import com.opensymphony.xwork2.ModelDriven;
import com.service.FileBagService;
//该类支持多文件上传
public class FileUploadAction extends BaseAction {
@Autowired
private FileBagService fileBagService;
private List<File> file; //Struts2文件上传不可缺少
private List<String> fileFileName; //Struts2文件上传不可缺少
private List<String> fileContentType; //Struts2文件上传不可缺少
private List<String> fileremark;
public List<File> getFile() {
return file;
}
public void setFile(List<File> file) {
this .file = file;
}
public List<String> getFileFileName() {
return fileFileName;
}
public void setFileFileName(List<String> fileFileName) {
this .fileFileName = fileFileName;
}
public List<String> getFileContentType() {
return fileContentType;
}
public void setFileContentType(List<String> fileContentType) {
this .fileContentType = fileContentType;
}
/**
* 执行文件上传的操作,会自动生成一个带随机文件名的字符串来防止重复文件。
*/
public String execute() throws Exception {
for ( int i = 0 ; i < file.size(); i++) {
FileBag fileBag = new FileBag(); //创建一个新的实例存储文件信息
fileBag.setFileIndate( new Date()); //设定文件上传日期
fileBag.setFileMark(fileremark.get(i)); //设定文件的备注信息
fileBag.setFileName(fileFileName.get(i)); //设定文件的真实名称
fileBag.setDownloadCount( 0 ); //设定文件下载次数为0
fileBag.setFileSize(file.get(i).length()+ "" );
String fileRandomName = StringUtils.randomString( 20 ); //随机产生文件名称的字符串
fileBag.setFilePath(fileRandomName); //设定文件的随机名称
fileBag.setFileType( this .fileContentType.get(i)); //设定文件类型
InputStream in = new FileInputStream(file.get(i));
//从Configuration类中获取设定的文件存储路径(常量),下载的时候也会用到这个存储地址
String root = Configuration.getValue( "fileSaveDir" );
File file = new File(root);
if (!file.exists()){ //如果目录不存在,则会重新创建目录
file.mkdirs();
System.out.println( "重新创建目录!" );
}
File destFile = new File(root, fileRandomName);
OutputStream out = new FileOutputStream(destFile);
byte [] b = new byte [ 1024 ];
int length = 0 ;
while ((length = in.read(b)) > 0 ) {
out.write(b, 0 , length);
}
in.close();
out.close();
fileBagService.save(fileBag);
}
this .msg= this .file.size()+ "个文件上传成功!" ;
return SUCCESS;
}
public List<String> getFileremark() {
return fileremark;
}
public void setFileremark(List<String> fileremark) {
this .fileremark = fileremark;
}
}
|