servlet+uploadify+commons-fileupload实现文件上传

来源:互联网 发布:知乎怎么提问 编辑:程序博客网 时间:2024/05/19 07:10

  先吐槽一下使用那些没有完整API的jar包,一步一个坑,网上很多代码都是有bug的,拿来主义+清除bug!

  1.commons-fileupload.jar在servlet中用来处理文件上传,比较简便,(尼玛,早知道用struts了,自己写一大堆什么获取参数,倒腾了好久,struts一个file映射,轻松搞定文件上传啊,为了用servlet实现,倒腾了一晚上。)主要注意在servlet中如何获取除了file文件以外的参数,http://www.thinkphp.cn/topic/9196.html该网址,说的很不清楚,有一个fileItem的getString方法,没有讲,http://blog.csdn.net/y_ber/article/details/5678979这篇文章讲了如何获取除了file以外的表单的其他控件的取值;

public voiddoPost(HttpServletRequest request, HttpServletResponse response)

                       throwsServletException, IOException {

        response.setContentType("text/html;charset=utf-8;");

       request.setCharacterEncoding("utf-8");

         StringprojectPath=this.getServletContext().getRealPath("/");

        String realName="";

        String savePath="";

        // new FileService().uploadFile(file,fileName, projectPath);

                        

                        SimpleDateFormat df = newSimpleDateFormat("yyyyMMddHHmmss");

                               StringextType ="";

                               StringnewHtmlName = "";

                               Stringsavepath= "";

               //此处调用commons-fileupload jar 完成文件的上传

               DiskFileItemFactoryfactory = new DiskFileItemFactory(); 

        //setting upload file path 

        factory.setRepository(new File(savepath));

        //set default memory size 

       factory.setSizeThreshold(1024*1024*10); 

        ServletFileUpload upload1 = newServletFileUpload(factory); 

       upload1.setHeaderEncoding("utf-8");//这一句可以解决中文乱码的问题

        try {

               List<FileItem> list  = upload1.parseRequest(request);

               for (FileItem item : list){ 

                      if(item.isFormField()){ //过滤掉表单中非文件域

                             String name =item.getFieldName();//input name

                             String value =item.getString();//input content ,注意此处是调用getString方法获取控件中的值

                         request.setAttribute(name, value); 

                      }else{

                      String name =item.getFieldName();//input name

                      String value =item.getName();//input content

                      realName =value.substring(value.lastIndexOf("\\")+1,value.length());  //此处获取的是上传的文件名

                      extType =realName.substring(realName.lastIndexOf(".") + 1)        .toLowerCase();//获取扩展类型

                      newHtmlName =df.format(new Date()) + "_" + new Random().nextInt(1000)

                                     +"." + extType;//新命名扩展类型

                      savepath= new FileService().getStoreRealPath(projectPath)+"\\"+newHtmlName;

                     

                      OutputStreamfileOutStream = new FileOutputStream(new File(savepath)); 

                      InputStreamfileInputStream = item.getInputStream();

                      //file buffer

                      byte [] buffer = newbyte[1024]; 

                      //read 

                      int length = 0;

                      while(( length =fileInputStream.read(buffer)) > 0){

                            fileOutStream.write(buffer,0,length); 

                             } 

                  //close 

                     fileInputStream.close(); 

                     fileOutStream.close(); 

                      item.write(newFile(savepath));

                      } 

               }

        } catch (Exception e) { 

               e.printStackTrace(); 

        } 

        StringfileName=request.getParameter("paperfileFileName");

                String paperid=(String) request.getAttribute("paperId");

                System.out.println(realName+"   "+paperid);

        }

 

2.uploadify官网http://www.uploadify.com/   api神马的比较简单,版本不同,传入的参数区别也很大,此处要特别注意,动态传入formDate参数使用的方法(红色区域)是:

$("#paperfile").uploadify({

               'debug':'true',

        'auto':true,

        'buttonText':"选择文件",

        'debug':false,

        'fileTypeDesc': 'Image Files',

        'fileTypeExts': '*.*',       

        'successTimeout': 1000,

        'button_image_url':'js/uploadify/uploadify.png',//此属性必须要设置,否则就会在初始化完控件以后去请求一个空action,后台会报错。

        'buttonImage': 'js/uploadify/browse-btn.png',

        'fileObjName':'paperfile',

        'simUploadLimit': 1, // 一次同步上传的文件数目

        'uploader':'uploadFileServlet',

        'swf':'js/uploadify/uploadify.swf',

        'onUploadSuccess':function ( fileObj, data, response) {

               alert("success");

               /*varmyobj = eval('(' + data + ')');// eval将json字符串装换成js对象。必须加入(),eval才不会将{}内的内容当成语句执行

                                              $("#adverPrepic").attr("src",'../../../myFile/AdsPicture/'+myobj.pathinfo);

                                              $("#adverPicPath").val(myobj.pathinfo);*/

                                              }, 

        'onUploadError':function(event, queueID, fileObj) { 

                                                             alert("文件:" + fileObj.name + "上传失败"); 

                                              },

        'onSelect':function(file){

                                                     $("#paperfile").uploadify("settings","formData", {'paperId':paperIdForFileUpload});  

                                              }                                    

        });

 

 

0 0