.文件的上传和下载:

.文件的上传和下载:

实例一:
不用struts2,用apache的fileupload组件上传:
jsp页面:
<form action="...." enctype="multipart/form-data">
  username:<input type="text" name="username">
  password:<input type="password" name="password">
  file1:<input type="file" name="file1">
  file2:<input type="file" name="file2">
</form>
servlet类:
public class UploadServlet extends HttpServlet{
public void post(....){
DiskFileItemFactory factory=new DiskFileItemFactory();
//获得绝对目录
String path=request.getRealPath("/upload");
//上传文件大的话,就会先存储在临时存储目录,然后在转到上传目录
factory.setRespository(new File(path));
//设定上传文件的大小,如果小于等于这个大小,就保存在内存里面,然后转到上传目录,如果大于这个大小,先存储到临时目录,然后在转到上传目录
factory.setSizeThreshold(1024*1024);
//创建实例
ServletFileUpload upload=new ServletFileUpload(factory);
try{
 //返回客户端上传的文件列表
 List<FileItem> list=upload.parseRequest(request);
 for(FileItem item:list){
   if(item.isFormField()){//是一般的类型
      //获得表单中定义的name
      String name=item.getFiledName();
      //获得用户输入的内容value
      String value=item.getString("gbk");
      request.setAttribute(name,value);     
   }else{
       //获得表单中定义的name
      String name=item.getFieledName();
      //获取上传文件的名字
      String value=item.getName();
      int start=value.lastIndexOf("//");
      String fileName=vlaue.substring(start+1);
      request.setAttribute(name,fileName);
    
      item.write(new File(path,fileName));
     或者
    //  OutputStream os=new FileOutputStream(new File(path,fileName));
    //  InputStream is=item.getInputStream();
   //   byte[] buffer=new byte[400];
   //   int length=0;
   //   while((length=is.read(buffer))>0){
    //    os.write(buffer,0,length);
   //   }
   //   os.close();
   //  is.close();
   }
 }
}catch(Exception e){
....
}
request.getRequestDispatcher("upload/reault2.jsp").forward(request,response);
}
}
实例二:
struts2实现文件上传:
上传一个文件:
public class UploadAction{
private String username;
private String password;
private File file;
private String fileFileName;
private String fileContentType;
//属性的get和set方法
.........
public String execute(){
    InputStream is=ne FileInputStream(file);
    String root=ServletActionContext.getRequest.getRealPath(/upload);
    File destFile=new File(root,this.getFileFileName());
    OutputStream os=new FileOutputStream(destFile);
 
   byte[] buffer=new byte[400];
    int length=0;
     while((length=is.read(buffer))>0){
     os.write(buffer,0,length);
    }
    os.close();
   is.close();
   return "success";
}
}
解决中文在struts.xml中加上:
<constant name="struts.i18n.encoding" value="gbk"/>
<constant name="struts.multipart.saveDir" value="c:/"/>
用户上传固定的几个文件:
public class UploadAction{
private String username;
private String password;
private List<File> file;
private List<String> fileFileName;
private List<String> fileContentType;
//属性的get和set方法
.........
public String execute(){
  for(int i=0;i<file.size();i++){
    InputStream is=ne FileInputStream(file.get(i));
    String root=ServletActionContext.getRequest.getRealPath(/upload);
    File destFile=new File(root,this.getFileFileName().get(i));
    OutputStream os=new FileOutputStream(destFile);
 
   byte[] buffer=new byte[400];
    int length=0;
     while((length=is.read(buffer))>0){
     os.write(buffer,0,length);
    }
    os.close();
   is.close();
 }
   return "success";
}
}
页面中有3个:都是<s:file name="file">

用户上传任意多个文件
jsp页面
<s:fieldError/>
<tr>
  <td>file</td>
  <td id="more">
<s:file name="file"><input οnclick="addMore()" type="button" value="Add More....">
   </td>
</tr>
js代码:
function addMore(){
 var td=document.getElementById("more");
 var br=document.createElement("br");
 var input=document.createElement("input");
 var button=document.createElement("input");
 input.type="file";
 input.name="file";
 button.type="button";
 button.value="Remove";
 button.οnclick=function(){
   td.removeChild(br);
   td.removeChild(input);
   td.removeChild(button);
 }
 td.appendChild(br);
 td.appendChild(input);
 td.appendChild(button);
}
Action服务器端代码:不用修改
限制用户上传的格式:
<action name="upload" class="....">
  <interceptor-ref name="fileUpload">
     <param name="maximumSize">409600<param>//每个文件的大小
     <!--文件类型从tomcat中conf的web.xml查出来-->
     <param name="allowedTypes">application/vnd.ms-powerpoint</param>
  </interceptor> 
   <interceptor-ref name="defaultStack"/>
</action>
想改变错误提示信息:
<!--定义国际化资源文件-->
<constant name="name.custom.il8n.resuources" value="message"/>
message.properties文件放在classpath下面
#类型转化出问题的话就会是下面的提示信息了
struts.messages.error.content.type.not.allowed=the fiel type is error
struts.messages.error.file.too.large=the file is too large
 
用户下载:
public class DownloadAction{
//和配置文件的inputName同样
public InputStream getDownloadFile(){
  return ServlerActionContext.getServletContext.getResourceAsStream("/upload.struts.ppt");
}
public String execute(){
return success;
}
}
配置文件struts.xml
<action name="" class="">
  <result name="success" type="stream">
     <param name="contentType">application/vnd.ms-powerpoint</param>
     <param name="contentDisposition">filename="struts2.ppt"</param>
     <param name="inputName">downloadFile</param>    
  </result>
</action>
对于下载的文件名,下载的文件类型都是在struts.xml文件中配置的,如果有不同的类型的文件要提供给用户下载,那么这种方式显然有失灵活性。
   为了动态的设置文件类型和下载的文件名,我们可以编写 一个拦截器,在action执行完毕,result执行之前,动态添加StreamResult参数。
public class FileDownloadInterceptor extends Abstracterceptor{
public String interceptor(ActionInvocation invocation)throws Exception{
incocation.addPreResultListener(new PreResultListener(){
public void beforeResult(ActionInvocation invocation,String resultCode){
Map<String,ResultConfig> resultMap=invocation.getProxy().getConfig().getResults();
ResultConfig finalResultConfig=resultMap.get(resultCode);
//为了简单起见,我们硬编码了下载文件的类型和下载文件名,实际应用中你可以读取数据库或者配置文件来获取下载文件的信息
finalResultConfig.addParam("contentType",application/zip);
fianlResultConfig.addparam("contentDisposition","attachment;filename=/"abc.zip/"");
}
});
return invocation.invoke();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值