HttpURLConnection以使用参数may(String或Json String)发送图像,音频和视频文件 [英] HttpURLConnection to Send image , audio and video files with parameter may (String or Json String) Android

查看:87
本文介绍了HttpURLConnection以使用参数may(String或Json String)发送图像,音频和视频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在共享解决方案,以使用以下参数发送带有参数的图像音频视频文件 HttpURLConnection .参数可以是(纯字符串或JSON).

I'm sharing the solution to send an image , audio or a video file with parameters using HttpURLConnection. Parameters may be (plain string or JSON).

(Android客户端到PHP后端)

(Android Client to PHP Back end)

场景: 必须上传媒体文件(带有参数的音频,视频和图像).

Scenario: Have to upload media files (audio , video and image with parameters).

媒体文件将存储在服务器文件夹中,并将参数存储到db.

Media files will be stored in a server folder and parameters to db.

我遇到的一个问题是,图像已成功上传,而参数丢失了.

I faced a problem that, image was uploaded successfully while parameters went missing.

找到了可能的解决方案

选择 HttpURLConnection 而不是 Httpclient 作为您可能想知道,哪个客户最好?

You may be wondering, Which client is best?

Apache HTTP客户端在Eclair和Froyo上的错误较少.这是这些版本的最佳选择.

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.

对于姜饼和更好的产品,HttpURLConnection是最佳选择.其简单的API和较小的尺寸使其非常适合Android.透明的压缩和响应缓存减少了网络使用,提高了速度并节省了电池.新应用程序应使用HttpURLConnection;这是我们将继续努力的地方.

For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.

Android代码:

Android Code:

public int uploadFile(final String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :" + filepath);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :" + filepath);
            }
        });

        return 0;

    } else {
        try {
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
        //  conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);


            dos = new DataOutputStream(conn.getOutputStream());


            dos.writeBytes(twoHyphens + boundary + lineEnd);

//Adding Parameter name

            String name="amir";
            dos.writeBytes("Content-Disposition: form-data; name=\"name\"" + lineEnd); 
            //dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
            //dos.writeBytes("Content-Length: " + name.length() + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(name); // mobile_no is String variable
            dos.writeBytes(lineEnd);

            dos.writeBytes(twoHyphens + boundary + lineEnd);

//Adding Parameter phone
            String phone="9956565656";
            dos.writeBytes("Content-Disposition: form-data; name=\"phone\"" + lineEnd); 
            //dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
            //dos.writeBytes("Content-Length: " + name.length() + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(phone); // mobile_no is String variable
            dos.writeBytes(lineEnd);


            //Json_Encoder encode=new Json_Encoder();
            //call to encode method and assigning response data to variable 'data'
            //String data=encode.encod_to_json();
            //response of encoded data
            //System.out.println(data);


                //Adding Parameter filepath

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            String filepath="http://192.168.1.110/echo/uploads"+fileName;

            dos.writeBytes("Content-Disposition: form-data; name=\"filepath\"" + lineEnd); 
            //dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
            //dos.writeBytes("Content-Length: " + name.length() + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(filepath); // mobile_no is String variable
            dos.writeBytes(lineEnd);


//Adding Parameter media file(audio,video and image)

            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0)
            {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();



            Log.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {
                         msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                + "c:/wamp/www/echo/uploads";
                        messageText.setText(msg);
                        Toast.makeText(MainActivity.this,
                                "File Upload Complete.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText
                            .setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(MainActivity.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (final Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Got Exception : "+e.toString());
                    Toast.makeText(MainActivity.this,
                            "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;
    }
}

Php代码:

$file_path = "uploads/";

//receive parameters

  $name=$_POST['name'];
  $phone=$_POST['phone'];
  $filepath=$_POST['filepath'];


   //receive media files(image , audio and video)

   $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
   if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) 
      {
      echo "Success";
      }

希望这会有所帮助.

任何查询都会问我.

推荐答案

您可以使用 Retrofit API调用.对Android的最低支持为2.3.请检查详细信息.

You can use Retrofit for API call. Minimum support for Android is 2.3. Please check details.

这篇关于HttpURLConnection以使用参数may(String或Json String)发送图像,音频和视频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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