无法使用多部分实体上传视频文件 [英] Unable to Upload Video File using Multipart Entity

查看:207
本文介绍了无法使用多部分实体上传视频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Multipart Entity上传视频文件。对于使用Multipart Entity方法,有人提到我应该是以下jar文件httpclient,httpmime,httpcore。但是在添加httpcore jar文件时,我无法运行我的项目,并且会在我的控制台中引发以下错误。在卸载这个特定的jar时,当我尝试运行我的应用程序时,我的日志显示以下错误



这是我的代码供您参考:

  public class UploadActivity extends Activity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();

private ProgressBar progressBar;
private String filePath = null;
私有TextView txtPercentage;
私人ImageView imgPreview;
私人VideoView vidPreview;
private Button btnUpload;
long totalSize = 0;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
txtPercentage =(TextView)findViewById(R.id.txtPercentage);
btnUpload =(Button)findViewById(R.id.btnUpload);
progressBar =(ProgressBar)findViewById(R.id.progressBar);
imgPreview =(ImageView)findViewById(R.id.imgPreview);
vidPreview =(VideoView)findViewById(R.id.videoPreview);

//更改操作栏背景颜色
/ *
* getActionBar()。setBackgroundDrawable(new
* ColorDrawable(Color.parseColor(getResources()。getString
* R.color.action_bar))));
* /

//接收以前活动的数据
Intent i = getIntent();

//以前活动中捕获的图像或视频路径
filePath = i.getStringExtra(filePath);

//布尔标志来标识媒体类型,图像或视频
boolean isImage = i.getBooleanExtra(isImage,true);

if(filePath!= null){
//在屏幕上显示图像或视频
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
对不起,文件路径丢失!,Toast.LENGTH_LONG).show();
}

btnUpload.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v){
//将文件上传到服务器
new UploadFileToServer()。execute();
}
});

}

/ **
*在屏幕上显示捕获的图像/视频
* * /
private void previewMedia(boolean isImage ){
//检查捕获的媒体是图像还是视频
if(isImage){
imgPreview.setVisibility(View.VISIBLE);
vidPreview.setVisibility(View.GONE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();

//当调整大小的图像时,它会抛出OutOfMemory大的
//图像的异常
options.inSampleSize = 8;

final Bitmap bitmap = BitmapFactory.decodeFile(filePath,options);

imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
vidPreview.setVisibility(View.VISIBLE);
vidPreview.setVideoPath(filePath);
//开始玩
vidPreview.start();
}
}

/ **
*将文件上传到服务器
* * /
私有类UploadFileToServer扩展AsyncTask< Void,整数,字符串> {
@Override
protected void onPreExecute(){
//将进度条设置为零
progressBar.setProgress(0);
super.onPreExecute();
}

@Override
protected void onProgressUpdate(Integer ... progress){
//使进度条可见
progressBar.setVisibility(View。可见);

//更新进度条值
progressBar.setProgress(progress [0]);

//更新百分比值
txtPercentage.setText(String.valueOf(progress [0])+%);
}

@Override
protected String doInBackground(Void ... params){
return uploadFile();
}

@SuppressWarnings(deprecation)
private String uploadFile(){
String responseString = null;

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

尝试{
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener(){

@Override
public void transfers(long num) {
publishProgress((int)((num /(float)totalSize)* 100));
}
});

文件sourceFile = new File(filePath);

//将文件数据添加到http body
entity.addPart(image,新的FileBody(sourceFile));

//如果要传递到服务器
entity.addPart(website,
new StringBody(www.androidhive.info))的额外参数;
entity.addPart(email,new StringBody(abc@gmail.com));

totalSize = entity.getContentLength();
httppost.setEntity(entity);

//使服务器调用
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();

int statusCode = response.getStatusLine()。getStatusCode();
if(statusCode == 200){
//服务器响应
responseString = EntityUtils.toString(r_entity);
} else {
responseString =发生错误!Http状态码:
+ statusCode;
}

} catch(ClientProtocolException e){
responseString = e.toString();
} catch(IOException e){
responseString = e.toString();
}

return responseString;

}

@Override
protected void onPostExecute(String result){
Log.e(TAG,从服务器响应+结果) ;

//在警报对话框中显示服务器响应
showAlert(result);

super.onPostExecute(result);
}

}

/ **
*显示警报对话框的方法
* * /
private void showAlert String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle(从服务器响应)
.setCancelable(false)
.setPositiveButton(OK,new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id){
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}

}



任何人都可以帮我解决问题吗?就像为什么当我尝试添加Httpcore jar的时候我收到这个错误,我该怎么克服这些...?



还是有任何替代的,我做使其工作????

解决方案

以下代码经过测试,适用于从Android上传视频。



Knossos在对您的问题的评论中说,现在Android中有更新,更推荐的HTTP库,尽管您可能需要检查他们正确处理多路消息。在Android中有一个很好的概述(有一个有趣的历史)在这里: https://packetzoom.com/blog/which-android-http-library-to-use.html

  import java.io.File; 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.util.Log;

public class VideoUploadTask extends AsyncTask< String,String,Integer> {
/ *这个类是一个AsynchTask将视频上传到后台线程上的服务器
*
* /

private VideoUploadTaskListener thisTaskListener;
private String serverURL;
private String videoPath;

public VideoUploadTask(VideoUploadTaskListener ourListener){
//构造函数
Log.d(VideoUploadTask,constructor);

//设置监听器
thisTaskListener = ourListener;
}

@Override
protected Integer doInBackground(String ... params){
//在后台上传视频
Log.d VideoUploadTask, doInBackground);

//从参数
获取服务器URL和本地视频路径if(params.length == 2){
serverURL = params [0];
videoPath = params [1];
} else {
//一个或所有参数不存在 - 记录错误并返回
Log.d(VideoUploadTask doInBackground,一个或所有参数不是当下);
return -1;
}


//创建一个新的Multipart HTTP请求上传视频
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(serverURL);

//创建一个Multipart实体并添加零件
try {
Log.d(VideoUploadTask doInBackground,构建文件请求+ videoPath) ;
FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody(Filename:+ videoPath);
StringBody description = new StringBody(Test Video);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart(videoFile,filebodyVideo);
reqEntity.addPart(title,title);
reqEntity.addPart(description,description);
httppost.setEntity(reqEntity);
} catch(UnsupportedEncodingException e1){
//记录错误
Log.d(VideoUploadTask doInBackground,设置StringBody为标题或描述时为UnsupportedEncodingException错误);
e1.printStackTrace();
return -1;
}

//将请求发送到服务器
HttpResponse serverResponse = null;
尝试{
Log.d(VideoUploadTask doInBackground,发送请求);
serverResponse = httpclient.execute(httppost);
} catch(ClientProtocolException e){
//记录错误
Log.d(VideoUploadTask doInBackground,ClientProtocolException);
e.printStackTrace();
} catch(IOException e){
//记录错误
Log.d(VideoUploadTask doInBackground,IOException);
e.printStackTrace();
}

//检查响应代码
Log.d(VideoUploadTask doInBackground,检查响应代码);
if(serverResponse!= null){
Log.d(VideoUploadTask doInBackground,ServerRespone+ serverResponse.getStatusLine());
HttpEntity responseEntity = serverResponse.getEntity();
if(responseEntity!= null){
//记录响应代码并消耗内容
Log.d(VideoUploadTask doInBackground,responseEntity is not null);
try {
responseEntity.consumeContent();
} catch(IOException e){
//记录(进一步...)错误...
Log.d(VideoUploadTask doInBackground,IOexception消费内容);
e.printStackTrace();
}
}
} else {
//记录响应代码为空
Log.d(VideoUploadTask doInBackground,serverResponse = null);
return -1;
}

//关闭连接管理器
httpclient.getConnectionManager().shutdown();
return 1;
}

@Override
protected void onPostExecute(Integer result){
//检查返回代码并更新监听器
Log.d( VideoUploadTask onPostExecute,执行后更新侦听器);
thisTaskListener.onUploadFinished(result);
}

}


I'm trying to upload an video file using Multipart Entity. For using Multipart Entity method, it was mentioned that I should the following jar files httpclient, httpmime, httpcore. But on adding the httpcore jar file I couldn't run my project and it throws the following error in my console.

On removing this particular jar, when I try to run my application my log shows the following error in my code.

here's my code for your reference:

public class UploadActivity extends Activity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();

private ProgressBar progressBar;
private String filePath = null;
private TextView txtPercentage;
private ImageView imgPreview;
private VideoView vidPreview;
private Button btnUpload;
long totalSize = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);
    txtPercentage = (TextView) findViewById(R.id.txtPercentage);
    btnUpload = (Button) findViewById(R.id.btnUpload);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    imgPreview = (ImageView) findViewById(R.id.imgPreview);
    vidPreview = (VideoView) findViewById(R.id.videoPreview);

    // Changing action bar background color
    /*
     * getActionBar().setBackgroundDrawable( new
     * ColorDrawable(Color.parseColor(getResources().getString(
     * R.color.action_bar))));
     */

    // Receiving the data from previous activity
    Intent i = getIntent();

    // image or video path that is captured in previous activity
    filePath = i.getStringExtra("filePath");

    // boolean flag to identify the media type, image or video
    boolean isImage = i.getBooleanExtra("isImage", true);

    if (filePath != null) {
        // Displaying the image or video on the screen
        previewMedia(isImage);
    } else {
        Toast.makeText(getApplicationContext(),
                "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
    }

    btnUpload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // uploading the file to server
            new UploadFileToServer().execute();
        }
    });

}

/**
 * Displaying captured image/video on the screen
 * */
private void previewMedia(boolean isImage) {
    // Checking whether captured media is image or video
    if (isImage) {
        imgPreview.setVisibility(View.VISIBLE);
        vidPreview.setVisibility(View.GONE);
        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // down sizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        imgPreview.setImageBitmap(bitmap);
    } else {
        imgPreview.setVisibility(View.GONE);
        vidPreview.setVisibility(View.VISIBLE);
        vidPreview.setVideoPath(filePath);
        // start playing
        vidPreview.start();
    }
}

/**
 * Uploading the file to server
 * */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        // setting progress bar to zero
        progressBar.setProgress(0);
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // Making progress bar visible
        progressBar.setVisibility(View.VISIBLE);

        // updating progress bar value
        progressBar.setProgress(progress[0]);

        // updating percentage value
        txtPercentage.setText(String.valueOf(progress[0]) + "%");
    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new ProgressListener() {

                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });

            File sourceFile = new File(filePath);

            // Adding file data to http body
            entity.addPart("image", new FileBody(sourceFile));

            // Extra parameters if you want to pass to server
            entity.addPart("website",
                    new StringBody("www.androidhive.info"));
            entity.addPart("email", new StringBody("abc@gmail.com"));

            totalSize = entity.getContentLength();
            httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            }

        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }

        return responseString;

    }

    @Override
    protected void onPostExecute(String result) {
        Log.e(TAG, "Response from server: " + result);

        // showing the server response in an alert dialog
        showAlert(result);

        super.onPostExecute(result);
    }

}

/**
 * Method to show alert dialog
 * */
private void showAlert(String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(message).setTitle("Response from Servers")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // do nothing
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
}

}

Can anyone please help me solving the issue? Like why I'm getting this error when I try to add Httpcore jar, how can I overcome these...???

Or is there any alternate that I do to make it work????

解决方案

The following code is tested and works for uploading video from Android.

It is worth nothing, as Knossos says in the comments to your question, that there are newer, more recommended libraries for HTTP in Android these days, although you may would need to check that they handle Multipart messages properly. A good overview of HTTP in Android (which has an interesting history) is here: https://packetzoom.com/blog/which-android-http-library-to-use.html

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.util.Log;

public class VideoUploadTask extends AsyncTask<String, String, Integer> {
    /* This Class is an AsynchTask to upload a video to a server on a background thread
     * 
     */

    private VideoUploadTaskListener thisTaskListener;
    private String serverURL;
    private String videoPath;

    public VideoUploadTask(VideoUploadTaskListener ourListener) {
        //Constructor
        Log.d("VideoUploadTask","constructor");

        //Set the listener
        thisTaskListener = ourListener;
    }

    @Override
    protected Integer doInBackground(String... params) {
        //Upload the video in the background
        Log.d("VideoUploadTask","doInBackground");

        //Get the Server URL and the local video path from the parameters
        if (params.length == 2) {
            serverURL = params[0];
            videoPath = params[1];
        } else {
            //One or all of the params are not present - log an error and return
            Log.d("VideoUploadTask doInBackground","One or all of the params are not present");
            return -1;
        }


        //Create a new Multipart HTTP request to upload the video
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(serverURL);

        //Create a Multipart entity and add the parts to it
        try {
            Log.d("VideoUploadTask doInBackground","Building the request for file: " + videoPath);
            FileBody filebodyVideo = new FileBody(new File(videoPath));
            StringBody title = new StringBody("Filename:" + videoPath);
            StringBody description = new StringBody("Test Video");
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("videoFile", filebodyVideo);
            reqEntity.addPart("title", title);
            reqEntity.addPart("description", description);
            httppost.setEntity(reqEntity);
        } catch (UnsupportedEncodingException e1) {
            //Log the error
            Log.d("VideoUploadTask doInBackground","UnsupportedEncodingException error when setting StringBody for title or description");
            e1.printStackTrace();
            return -1;
        }

        //Send the request to the server
        HttpResponse serverResponse = null;
        try {
            Log.d("VideoUploadTask doInBackground","Sending the Request");
            serverResponse = httpclient.execute( httppost );
        } catch (ClientProtocolException e) {
            //Log the error
            Log.d("VideoUploadTask doInBackground","ClientProtocolException");
            e.printStackTrace();
        } catch (IOException e) {
            //Log the error
            Log.d("VideoUploadTask doInBackground","IOException");
            e.printStackTrace();
        }

        //Check the response code
        Log.d("VideoUploadTask doInBackground","Checking the response code");
        if (serverResponse != null) {
            Log.d("VideoUploadTask doInBackground","ServerRespone" + serverResponse.getStatusLine());
            HttpEntity responseEntity = serverResponse.getEntity( );
            if (responseEntity != null) {
                //log the response code and consume the content
                Log.d("VideoUploadTask doInBackground","responseEntity is not null");
                try {
                    responseEntity.consumeContent( );
                } catch (IOException e) {
                    //Log the (further...) error...
                    Log.d("VideoUploadTask doInBackground","IOexception consuming content");
                    e.printStackTrace();
                }
            } 
        } else {
            //Log that response code was null
            Log.d("VideoUploadTask doInBackground","serverResponse = null");
            return -1;
        }

        //Shut down the connection manager
        httpclient.getConnectionManager( ).shutdown( ); 
        return 1;
    }

    @Override
    protected void onPostExecute(Integer result) {
        //Check the return code and update the listener
        Log.d("VideoUploadTask onPostExecute","updating listener after execution");
        thisTaskListener.onUploadFinished(result);
    }

}

这篇关于无法使用多部分实体上传视频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆