smartupload实现文件上传时获取表单数据(推荐)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

smartupload实现文件上传时获取表单数据(推荐)

heartbeaty   2020-05-15 我要评论

实现文件上传的form表单必须满足两个条件:method="post" enctype="multipart/form-data"

表单中enctype="multipart/form-data"的意思是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据。enctype="multipart/form-data"是上传二进制数据; form里面的input的值以二进制的方式传过去。所以request就得不到值了, 也就是说加了这段代码,用request就会传递不成功。

取表单字段值时,用下面的方式:

SmartUpload su = new SmartUpload(); //新建一个SmartUpload对象 
su.getRequest().getParameterValues(String name); //取数组值  
su.getRequest().getParameter(String name); //取单个参数单个值 

注:在使用SmartUpload时需要添加相应的jar包

String softname=su.getRequest().getParameter("softname");

注意:一定要在su.upload();,之后使用,才可以获得值!!

<span style="font-size:14px;">public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
      SmartUpload mySmartUpload = new SmartUpload(); 
      try{ 
        // Initialization 
        mySmartUpload.initialize(config,request,response); 
        mySmartUpload.setMaxFileSize(10*1024*1024);//限制上传文件的大小 
        //mySmartUpload.setAllowedFilesList("txt,html,jpg,js");//设置允许上传的文件类型 
        mySmartUpload.setDeniedFilesList("exe,doc");//设置禁止上传的文件列表 
        mySmartUpload.upload(); 
        String hString = mySmartUpload.getRequest().getParameter("name1"); 
        //System.out.println(hString); 
        //System.out.println(mySmartUpload.getFiles().getCount()); 
        for(int i = 0 ;i <mySmartUpload.getFiles().getCount();i++){//多个文件的上传 
          File file = mySmartUpload.getFiles().getFile(i); 
          if(file.getSize()!=0){ 
            //拼凑上传文件的新名称 
            String fileNameString = System.currentTimeMillis()+"."+file.getFileExt(); 
            //通过servlet的实际路径拼凑上传文件的保存路径,实际使用需要修改此路径 
            String path = "/upload123123"+java.io.File.separator+fileNameString; 
            file.saveAs(path); 
          } 
          Thread.sleep(100); 
          /*下载文件的语句 
          mySmartUpload.downloadFile("/路径"+"文件名称");*/ 
        } 
      }catch(Exception e){ 
        e.printStackTrace(); 
      } 
  }</span> 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们