文件上传下载Struts2.docx
- 文档编号:20132829
- 上传时间:2023-04-25
- 格式:DOCX
- 页数:10
- 大小:17.89KB
文件上传下载Struts2.docx
《文件上传下载Struts2.docx》由会员分享,可在线阅读,更多相关《文件上传下载Struts2.docx(10页珍藏版)》请在冰豆网上搜索。
文件上传下载Struts2
多附件的上传下载--代码可直接用
分类:
java2011-06-0210:
033520人阅读评论(0)收藏举报
stringfileexceptioninputuploadbyte
action中的代码
try{
// 多附件上传
MultipartRequestHandlermrh=conForm.getMultipartRequestHandler();
MapformFiles=mrh.getFileElements();
StringfileName="";
if(formFiles!
=null){
AnnexsUploadau=newAnnexsUpload(req,res);//获得上传附件通用对象
Iteratorit=formFiles.values().iterator();
while(it.hasNext()){
//图片上传
FormFilefile=(FormFile)it.next();
au.setSaveDir(this.servlet.getServletContext().getRealPath("/loadImage/"));//将图片放入存储文件路径
fileName=au.randomFileName(file.getFileName());
au.upload(au.getSaveDir()+File.separator+fileName,fileName,file);//上传附件
//保存记录
IAttachmentDAOia=newAttachmentDAO();
TabAttachmentatt=newTabAttachment();
att.setFieldId(con.getCoid());//把资讯表的id添加到附件表里面
att.setTableName(tableName); //关联的表名
att.setAttachFile(fileName); //上传到服务器的文件名
att.setRemark(file.getFileName());//文件原来的真名
att.setUploadName(user.getRealname());//上传者,即登录者姓名
ia.addAttachment(att);
}
}
}catch(Exceptione){
}
AnnexsUpload.java
packagem;
importjava.io.BufferedInputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.io.UnsupportedEncodingException;
import.MalformedURLException;
import.URL;
importjava.util.List;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importmons.fileupload.DiskFileUpload;
importmons.fileupload.FileItem;
importmons.fileupload.FileUploadException;
importorg.apache.struts.upload.FormFile;
publicclassAnnexsUpload{
privateHttpServletResponseresponse;
privateHttpServletRequestrequest;
privateStringsaveDir;//文件保存路径
privateStringoldFileName;//原始文件名
privateStringnewFileName;//新文件名
privateStringnewFilePath;//新文件路径
privatelongfileSize;//文件大小
privatelongmaxFileSize=1024*1024*20;//上传文件最大大小6M
privateintthresholdSize=4000;//起始大小
publicAnnexsUpload(HttpServletRequestrequest,HttpServletResponseresponse){
super();
this.response=response;
this.request=request;
}
//产生随机文件名
publicsynchronizedStringrandomFileName(StringfileName){
Stringtemp=fileName.substring(fileName.lastIndexOf("."));//得到文件扩展名
try{
Thread.sleep(10);//如果有多个线程同时上传就休眠1毫秒,这样就可以避免产生的文件名一样
}catch(InterruptedExceptione){
e.printStackTrace();
}
returnSystem.currentTimeMillis()+temp;
}
//文件目录不存在则创建
publicvoidsetSaveDir(StringsaveDir){
this.saveDir=saveDir;
Filef=newFile(this.saveDir);
if(!
(f.isDirectory())){
f.mkdirs();
}
}
//上传单个文件
publicbooleanupload(){
DiskFileUploaddfu=newDiskFileUpload();
dfu.setSizeMax(this.maxFileSize);//设置上传文件最大值
dfu.setSizeThreshold(this.thresholdSize);//设置初始大小
dfu.setRepositoryPath(this.newFilePath);//设置上传路径
Listlist=null;
try{
list=dfu.parseRequest(this.request);//解析request并且返回list集合
}catch(FileUploadExceptione){
e.printStackTrace();
}
// System.out.println(list.isEmpty());
for(inti=0;i FileItemfi=(FileItem)list.get(i); try{ //中文编码转换 this.oldFileName=newString(fi.getFieldName().getBytes(),"GB2312"); //得到原始文件名 this.oldFileName=this.oldFileName.substring(this.oldFileName.indexOf("//")+1); this.fileSize=fi.getSize(); if(this.fileSize>this.maxFileSize){ System.out.println("文件太大"); returnfalse; } this.newFileName=this.randomFileName(this.oldFileName); this.newFilePath=this.saveDir+this.newFileName; Filef=newFile(this.saveDir,this.newFileName); fi.write(f); }catch(UnsupportedEncodingExceptione){ e.printStackTrace(); returnfalse; }catch(Exceptione){ e.printStackTrace(); returnfalse; } } returntrue; } //上传新文件 /* publicbooleanupload(FormFilefile){ try{ this.fileSize=file.getFileSize(); if(this.fileSize>this.maxFileSize){ System.out.println("文件太大"); returnfalse; } this.oldFileName=newString(file.getFileName().getBytes(),"GB2312"); this.oldFileName=this.oldFileName.substring(this.oldFileName.lastIndexOf("//")+1); this.newFilePath=this.saveDir+"//"+this.randomFileName(this.oldFileName); this.newFileName=this.randomFileName(this.oldFileName); AnnexsBeanfb=newAnnexsBean(); fb.AddAnnexs(newAnnexs(this.newFilePath,this.newFileName,this.fileSize+"")); //构造输入流 BufferedInputStreambis=newBufferedInputStream(file.getInputStream(),(int)this.fileSize); Filef=newFile(this.newFilePath); FileOutputStreamfos=newFileOutputStream(f); byte[]b=newbyte[1024]; intlen=0; while((len=bis.read(b))>0){ fos.write(b,0,len);//从缓冲区里读取数据写入输出流 } fos.close(); bis.close(); returntrue; }catch(Exceptione){ e.printStackTrace(); returnfalse; } }*/ //以自定义的名称保存文件 publicbooleanupload(StringfilePath,StringfileName,FormFilefile){ this.fileSize=file.getFileSize(); if(this.fileSize>this.maxFileSize){ System.out.println("文件太大");//如果大于6M returnfalse; } this.oldFileName=file.getFileName(); this.newFileName=fileName; this.newFilePath=filePath; try{ BufferedInputStreambis=newBufferedInputStream(file.getInputStream(),(int)this.fileSize); Filef=newFile(this.newFilePath); FileOutputStreamfos=newFileOutputStream(f); byte[]b=newbyte[1024]; intlen=0; while((len=bis.read(b))>0){ fos.write(b,0,len); } fos.close(); bis.close(); returntrue; }catch(FileNotFoundExceptione){ e.printStackTrace(); returnfalse; }catch(IOExceptione){ e.printStackTrace(); returnfalse; } } //删除文件 publicstaticbooleandeleteFile(Stringpath){ Filef=newFile(path); if(f.exists()){ f.delete(); returntrue; }else returnfalse; } /** *删除文件 *@paramuploadPath文件的路径 *@paramfileName 文件名 */ publicstaticvoiddeleteFile(StringuploadPath,StringfileName){ Filefile=newFile(uploadPath+fileName); if(file.exists()){ file.delete(); }else{ // System.out.println(uploadPath+fileName+"文件不存在"); } } publicvoidsetSaveDirReport(StringsaveDir){ this.saveDir=saveDir; Filef=newFile(this.saveDir); if(f.isDirectory()){ f.mkdirs(); } } //文件下载 publicvoiddownload(StringfilePath,StringfileName,booleanisOnline){ Filefile=newFile(filePath); System.out.println(filePath); if(! file.exists()){ try{ thrownewException("文件不存在"); }catch(Exceptione){ e.printStackTrace(); } return; } try{ BufferedInputStreambis=newBufferedInputStream(newFileInputStream(file)); byte[]b=newbyte[1024]; intlen=0; response.reset(); if(isOnline){ URLurl=newURL("file: ///"+filePath); response.setContentType(url.openConnection().getContentType()); response.setHeader("Content-Disposition","inline;filename="+newString((fileName+filePath.substring(filePath.lastIndexOf("."))).getBytes(),"ISO-8859-1")); }else{ response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition","attachment;filename="+newString((fileName+filePath.substring(filePath.lastIndexOf("."))).getBytes(),"ISO-8859-1")); } OutputStreamout=response.getOutputStream(); while((len=bis.read(b))>0){ out.write(b,0,len); } out.close(); bis.close(); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(MalformedURLExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } } } jsp页面代码 forEachvar="listatt"items="${listAtt}"> 0px;">${listatt.remark} form111(${listatt.tatId})"> forEach> none;"id="PLList"class="chart_list"> 附件
functionform111(pid){
varimgdiv=$("#imgdiv"+pid);
varmdiv=$("#mdiv");
$.post('contentManage.do?
method=deleteFileUp&tatid='+pid,null,functioncallback1(data){});
imgdiv.hide();
//mdiv.text("删除成功!
").css("color","red");
}
down.jsp下载页面
<%@pagelanguage="java"pageEncoding="UTF-8"%>
<%@pageimport="com.jspsmart.upload.SmartUpload"%>
<%
//下载文件页面
SmartUploaddown=newSmartUpload();
//初始化环境
down.initialize(pageContext);
//得到下载文件参数名称
Stringfile=
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 文件 上传下载 Struts2