【问题标题】:Uploading large files with HttpClient使用 HttpClient 上传大文件
【发布时间】:2011-03-14 00:24:45
【问题描述】:

我想将带有HttpClient 的大型视频文件 (>=1Gb) 上传到 servlet,但我找不到任何实际示例。 能给我一些有用的代码示例吗?


我希望同时查看 HttpClient 和 FileUpload 演示代码(作为一个项目)。我可以使用 FileUpload lib 下载大文件吗?


像这样的小程序-> servlet 上传绑定很有趣

【问题讨论】:

    标签: java


    【解决方案1】:

    这里是一个HttpClient和文件上传的例子:

    http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload

    我不确定您所说的“真实”。它足够真实,即使它与您的情况不完全匹配。

    1GB?您可能会遇到文件大小限制问题。在本地试试看。如果它失败了,至少你会有一些真实的代码和更准确的条件可以在这里发布。

    【讨论】:

    • 感谢您的快速回复,我只找到了这个例子
    • 清单 9-6。 HttpMultiPartFileUpload.java
    • 这很有趣,但我没有看到任何关于块或缓冲区的提及?所以 HttpClient 没有 HttpUrlConnection max_chunk_size 限制?
    • 我找不到任何 FileUpload 示例 :( 所以我想查看客户端和 servlet 示例代码...
    【解决方案2】:

    我可以上传>200mb的大文件,请看下面的jsp到spring控制器代码。

    Jsp code :
    <script src="../lib/app/configurator.data.ajax.js" type="text/javascript"></script>
    <script src="../lib/ui/jquery.fileupload.js"></script>
    <html>
    
    <script language="Javascript">
    var varb = '';
    var test = 0;
    var count = 1;
    $(function () {
    var maxChunkSize = 30000000; //SET CHUNK SIZE HERE
    var your_global_var_for_form_submit = '';
    
    var params = {
            year: threeDSelectedYear,
            series: threeDSelectedSeries
    };
    /*File upload bind with form, 'fileupload' is my form id. As sumit triggers
        for file ulaod will submit my form*/
    /* replaceFileInput: true, */
    $('#fileupload').fileupload({
    maxChunkSize: maxChunkSize,
    url: efccustom.getEfcContext()+'upload/uploadZip?year='+threeDSelectedYear+'&series='+threeDSelectedSeries,             //URL WHERE FILE TO BE UPLOADED
        error: function (jqXHR, textStatus, errorThrown) {
        // Called for each failed chunk upload
            $(".fileupload-loading").html("");
             $('.ANALYZE_DIALOG').dialog("close");       
        },
    
        success: function (data, textStatus, jqXHR) {
        /*This event will be called on success of upload*/
        count = parseInt($('#counter').val()) + 1;
        $('#counter').val(count);
    
        $('#ttk').val(count);
        data.ttk = 7;
        console.log(" count ",count , data);
        },
    
        submit: function (e, data) {
        /*This event will be called on submit here i am
                         adding variable to form*/
        //console.log($('#zip_uploaded_file').val());      
    
        //console.log(data.originalFiles[0].name);            
        test = data.originalFiles[0];
        $('#fname').val(data.originalFiles[0].name);
        $('#trequests').val(Math.ceil(data.originalFiles[0].size/maxChunkSize));
        $('#counter').val('1');
        },
    
        progress: function (e, data) {
        /*PROGRESS BAR CODE WILL BE HERE */
            $(".fileupload-loading").html('<img src="../public/themeroller/images/throbber.gif" alt="Uploading Please Wait..." title="Uploading Please Wait...." />');       
        },
    
        add: function (e, data) {
        $('.browsedFileName').html(data.originalFiles[0].name);
        your_global_var_for_form_submit = data;
        },
    
        done: function (e, data) {
    
            ajaxcall.Data._get('upload/extractZipNCreateJson',params,function(data2) {
                alert("file upload success ");
                 $(".fileupload-loading").html("");
                 $('.ANALYZE_DIALOG').dialog("close");
            });
    
    
        }
    
    });
    /*This is my button click event on which i am submitting my form*/
      $('#button').click(function(){
        your_global_var_for_form_submit.submit();
      });
    });
    </script>
    
    <html>
    
    <body>
    
    
    <form id="fileupload" enctype="multipart/form-data"> 
    <div class="row fileupload-buttonbar">
    <div class="span7">
    <!--<input type="file" name="files" id="file" /> -->
    
    <input type="file" id="zip_uploaded_file"  name="zip_uploaded_file"  />
    <input type="hidden" name="counter" id="counter" value="1" />
    <input type="hidden" name="fname" id="fname" value="" />
    <input type="hidden" name="trequests" id="trequests" value="1" />
    
    <input type="hidden" name="ttk" id="ttk" value="1" />
    <input type="button" id="button" name="button" value="submit" />
     <span class='browsedFileName'></span>
    </div>
    </div>
    <!-- The loading indicator is shown during file processing -->
    <div class="fileupload-loading"></div>
    </form>
    </body>
    
    
    Controller COde :
    @RequestMapping(value = "/uploadZip", method = RequestMethod.POST, consumes = "multipart/form-data")
        @ResponseBody
        public ResponseEntity<String>
         uploadZip(HttpServletRequest request, HttpServletResponse response)
                throws IOException, IllegalArgumentException {
            try {       
            String year = request.getParameter("year");
            String series = request.getParameter("series");
            log.info(" year " + year + " series " + series);
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
    
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
    
                HttpSession session = request.getSession();
                UserContext userContext = (UserContext) session
                        .getAttribute(ApplicationConstant.USER_CONTEXT);
                String userName = userContext.getUser();
                String workSpaceInUse = userContext.getCurrentWorkSpace();           
                FileItem item = null;
                boolean fileNotExistFlag;
                String fileExtension;
                while (iterator.hasNext()) {
                    item = (FileItem) iterator.next();
    
                    String content = item.getContentType();
                    log.info(" content "+content);
                    log.info(" File Type Getting Uploaded :"+content);
                    if (!item.isFormField()) {
                /* Here in IOUtils the Third Parameter true tells that the small chunks of data that comes need to be added to the same File */
                IOUtils.copy(fileItem.getInputStream(), new FileOutputStream(new File(threeDPath+"/"+year+"/"+series+"/"+uploadZipFileName),true));               
                    }
                }
                return null;
            }   
            }
            catch(Exception e) {
                return handleError(new RuntimeException("Unexpected error while uploading ZIP", e));
            }
            return null;
        }
    

    【讨论】:

      猜你喜欢
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 2011-07-14
      相关资源
      最近更新 更多