您的位置:首页 > 编程语言 > Java开发

struts2多文件上传,并且上传文件说明

2013-04-04 08:29 351 查看
首先这里的很多方法都是我从其他博客中学习到的。但是我这次写的有些不同不仅可以上传多个文件,同时可以为文件添加说明,存入数据库中。

大致介绍:

struts2上传文件其实是先把文件放在临时文件当中,就是说先上传,再转移。所以在action中得到的files其实是临时文件的。

struts.xml中配置:

<!-- 零时路径存放处 -->

<constant name="struts.multipart.saveDir" value="c:/temp"/>

<!-- 最大接受数据 -->

<constant name="struts.multipart.maxSize" value="95000000" />

struts.xml中的package里面,加一个action

<action name="myFileUpload" class="fileUpload" method="uploadFile">

  <result name="success" type="redirectAction">enterUpload</result>

  <result name="input" type="redirectAction">enterUpload</result>

 

        <param name="savePath">/uploadFiles/</param>

     <param name="maximumSize">95000000</param>

     <param name="maxFileNum">20</param>

 </action>

注:class="fileUpload",这里就写java类的位置就行了,我的在spring.xml中配置了。

上面这些都没什么特别的,每个人和每个人的大体框架不同,不用太琢磨。

开始重点:

一个存file信息的java类,我的是

public class FileUploadInfo {
File file;
String fileFileName;
String fileContentType;
String state;
}

 

上面要加get和set方法。

在action里面:

  

Map<String,FileUploadInfo> files= new HashMap<String, FileUploadInfo>();//关键处,其实下面的都不用看了,都是根据我自己的需要的进行的处理。就是这个Map匹配,一直没有人想出用它。记得后面有get,set方法,用eclipse自动生成的那个就行
private ServletContext servletContext;
private String savePath;//="/uploadFiles/";//这个在action的配置文件中

FileUploadStatus status;
private List<String> myErrors= new ArrayList<String>();

IFileBiz fileBiz;
IUserBiz userBiz;
User user=new User();
long maximumSize;
Integer maxFileNum;
public String uploadFile() {
Integer amount=fileBiz.filesAmount();
myErrors.clear();
//myErrors= new ArrayList<String>();
myErrors.add("true");
if(amount>maxFileNum)
{
myErrors.add("服务器中文件数量过多,禁止上传,请联系管理员再上传");
return "success";
}
if(files==null)
{
myErrors.add("未成功上传任何文件,原因可能如下:");
myErrors.add("1.未选中任何文件");
myErrors.add("2.上传文件过大,该服务器不接受一次性大于  90M 的文件");
return "success";
}
/*
* if(isOverload()=="true")
{
return "success";
}
* */

myErrors.add("已上传的文件名如下:");
servletContext = ServletActionContext.getServletContext();
String path_date=new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
String path=savePath + path_date;
String dataRealPath = servletContext.getRealPath(path);
File savedir = new File(dataRealPath);
if(!savedir.exists()) savedir.mkdirs();
String fileRelPath;//数据库中保存的相对路径
String saveFilePath;//真正要保存的路径

MyFile myFile= new MyFile();
user=userBiz.getUserByName(CommonMethod.GainNowSessionUser().getUsername());

myFile.setUserName(CommonMethod.GainNowSessionUser().getUsername());
myFile.setUserId(user.getId());

FileUploadInfo fileInfo=null;
String fileName,describe;

Set<String> keys = files.keySet();
for (Iterator<String> it = keys.iterator(); it.hasNext();) {
String key = (String) it.next();
fileInfo=files.get(key);
fileName=fileInfo.getFileFileName();
describe=fileInfo.getState();
if(fileInfo.getFile()!=null)
{
if(maximumSize<fileInfo.getFile().length())continue;

myErrors.add(fileName);
Random random=new Random();
saveFilePath=dataRealPath+"/" + random.nextLong()+
fileName.substring(fileName.lastIndexOf("."));

while (new File(saveFilePath).exists()) {
saveFilePath = dataRealPath+"/" + random.nextLong()+
fileName.substring(fileName.lastIndexOf("."));
}

File saveFile = new File(savedir,saveFilePath.substring(
saveFilePath.lastIndexOf("/")+1));
try
{
//还是无法防止大文件
FileUtils.copyFile(fileInfo.getFile(), saveFile);
}catch(IOException e)
{
return "success";
}

myFile.setFileName(fileName);
fileRelPath=path_date+ saveFilePath.substring(
saveFilePath.lastIndexOf("/"));
myFile.setFilePath(fileRelPath);
if(describe!=null && describe.length()!=0)
{
myFile.setFileState(describe);
}
else
{
myFile.setFileState("暂无说明");
}

fileBiz.addFile(myFile);
userBiz.UorDloadTimesAdd(user, 'U');
HttpSession session=ServletActionContext.getRequest().getSession();
session.removeAttribute("currentUploadStatus");

}
}
myErrors.add("<br>");
myErrors.add("如有文件未上传,则可能因为文件过大被拒绝");
return "success";
}

jsp这里还是重点:

<form action="/file/myFileUpload" method="post" enctype="multipart/form-data"
onSubmit="return judge()">
<input type="file" name="files['0'].file">
<input type="button" value="添加更多文件">
<br>
为文件添加说明:<br>
<textarea name="files['0'].state"></textarea>
<div id="moreFile"></div>
<br>
<div id="fileStatus"></div>
<br><br>

<input style="clear:left;" type="submit" value="确定上传" onClick="return judge()">
</form>


 

后面的自己用js生成name="files['1'].file">,name="files['2'].file">就可以了。

那个上传文件显示进度的我也通过整合网上的资料做出来了,不过效果不太好,可能是我对jsp的流程掌握不好,有时间可以再把那个的实现写一下。

 

 

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息