上传包含视频的缩略图

时间:2018-05-05 15:34:04

标签: android

我可以录制视频并使用此代码将其上传到服务器

[I:]:                     Found Xamarin.Android 8.0.0.33
[I:sdk]:                  Runtime path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Xamarin\Android
[I:sdk]:                  Framework path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\MonoAndroid\v1.0
[I:sdk]:                    Key HKCU\SOFTWARE\Xamarin\VisualStudio\15.0_6c165955\Android\AndroidSdkDirectory found:
    Path contains adb in \platform-tools (C:\Program Files (x86)\Android\android-sdk).
[I:sdk]:                    Key HKCU\SOFTWARE\Xamarin\VisualStudio\15.0_6c165955\Android\AndroidNdkDirectory found:
    Path contains ndk-stack in \. (C:\ProgramData\Microsoft\AndroidNDK64\android-ndk-r13b).
[I:sdk]:                    Key HKCU\SOFTWARE\Xamarin\VisualStudio\15.0_6c165955\Android\JavaSdkDirectory found:
    Path contains jarsigner.exe in \bin (C:\Program Files\Java\jdk1.8.0_131).
[I:]:                     Found Android SDK. API levels: 22, 23, 24, 25

我可以从视频中获取图像并使用以下代码显示它:

public class MainActivity extends Activity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private Uri fileUri;
    private Button btnRecordVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
        btnRecordVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
            }
        });
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);


        fileUri = savedInstanceState.getParcelable("file_uri");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
 if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                new UploadFileToServer().execute();
            }
        }
    }

    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    private static File getOutputMediaFile(int type) {

        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                Config.IMAGE_DIRECTORY_NAME);

        File mediaFile = new File(mediaStorageDir.getPath() + "VID_.mp4");
        return mediaFile;
    }

    private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @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 AndroidMultiPartEntity.ProgressListener() {
                            @Override
                            public void transferred(long num) {

                            }
                        });

                File sourceFile = new File(fileUri.getPath());

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

                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);

            super.onPostExecute(result);
        }
    }
}

我的代码效果很好,

我想在将视频上传到服务器时从视频上传图片,但我不知道该怎么做

你能帮我吗?

抱歉我的英文不好

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

创建一个名为“UploadImageApacheHttp”的类,并将以下内容复制到其中。 在此之前,从这里下载Base64文件,其中包含Base64格式的编码。

添加到草图

android {
useLibrary ‘org.apache.http.legacy’
}

将其添加到您的项目中。

public class UploadImageApacheHttp {
 public static final String TAG = "Upload Image Apache";

    public void doFileUpload(final String url, final Bitmap bmp, final Handler handler){

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {

                Log.i(TAG, "Starting Upload...");
                final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("image", convertBitmapToString(bmp)));

                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(url);
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    String responseStr = EntityUtils.toString(response.getEntity());
                    Log.i(TAG, "doFileUpload Response : " + responseStr);
                    handler.sendEmptyMessage(1);
                } catch (Exception e) {
                    System.out.println("Error in http connection " + e.toString());
                    handler.sendEmptyMessage(0);
                }
            }
        });
        t.start();

    }

    public String convertBitmapToString(Bitmap bmp){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
        byte[] byte_arr = stream.toByteArray();
        String imageStr = Base64.encodeBytes(byte_arr);
        return imageStr;
    }
}

然后在主要活动中:

private void uploadImage() {


    UploadImageApacheHttp uploadTask = new UploadImageApacheHttp();
    uploadTask.doFileUpload(UPLOAD_URL, bitmap, handler);

}