Android:使用MultipartEntity上传大文件

3
根据"Android使用HTTP多部件表单数据上传视频到远程服务器"的回答,我执行了所有步骤。但是我不知道如何编写服务器端代码!我的意思是编写一个简单的PHP页面以响应我的上传请求。另一个问题是:下面代码段的第三行中的YOUR_URL必须是该PHP页面的地址吗?
private void uploadVideo(String videoPath) throws ParseException, IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(YOUR_URL);

    FileBody filebodyVideo = new FileBody(new File(videoPath));
    StringBody title = new StringBody("Filename: " + videoPath);
    StringBody description = new StringBody("This is a description of the video");

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("videoFile", filebodyVideo);
    reqEntity.addPart("title", title);
    reqEntity.addPart("description", description);
    httppost.setEntity(reqEntity);

    // DEBUG
    System.out.println( "executing request " + httppost.getRequestLine( ) );
    HttpResponse response = httpclient.execute( httppost );
    HttpEntity resEntity = response.getEntity( );

    // DEBUG
    System.out.println( response.getStatusLine( ) );
    if (resEntity != null) {
      System.out.println( EntityUtils.toString( resEntity ) );
    } // end if

    if (resEntity != null) {
      resEntity.consumeContent( );
    } // end if

    httpclient.getConnectionManager( ).shutdown( );
}
1个回答

5
这段代码运行良好,我应该使用的PHP代码就像这样简单:
<?php

    $file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['videoFile']['name']);
    if(move_uploaded_file($_FILES['videoFile']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "upload_fail_php_file";
    }
 ?>

注意,videoFile必须与以下代码完全匹配:

reqEntity.addPart("videoFile", filebodyVideo);

而你可能面临的最重要的问题是服务器配置中post_max_sizeupload_max_filesize的默认值过小。当您尝试上传大文件时,PHP脚本会返回"upload_fail_php_file"而不会抛出错误或异常。因此,请记得将这些值设置得足够大...

祝愉快编码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接