视频上传Android

时间:2014-04-17 06:34:06

标签: android

当我尝试上传大小超过20MB的视频时,服务器无法获取正在发送的任何参数。我发送视频和jsonobject作为字符串到服务器。使用httpmime-4.1.1 jar.Below是我的代码。我是Android开发的新手,任何帮助都会很明显。我需要快速解决方案。请帮帮我

String s = json;
Log.d("message", "s==="+s);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
StringBuilder sq = null;                                                                    // Limit

String result = null;
String result1 = null;
try {
    HttpPost post = new HttpPost(url);

    MultipartEntity reqEntity = new MultipartEntity(
            HttpMultipartMode.BROWSER_COMPATIBLE);



    Log.d("message","video"+ bin.getFilename());

    reqEntity.addPart("video",bin);



    reqEntity.addPart("arguments", new StringBody(s.toString()));           

    post.setEntity(reqEntity);
    int timeoutConnection = 60000;
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters,
            timeoutConnection);
    int timeoutSocket = 60000;

    HttpConnectionParams.setTcpNoDelay(httpParameters, true);

    try {
        HttpResponse response = client.execute(post);
        Log.v("@WebSErvice:"+response, "Result0" + response);
        if (response == null) {
            result = null;
        } else {

            try {
                TieWebServicesComponents BWSC = new TieWebServicesComponents(
                        TieWebServicesComponents.POST_TASK, mContext);
                result = BWSC.inputStreamToString(response.getEntity()
                        .getContent());
                Log.v("message:CommunityHome Response"+response, "Result1" + result);

            } catch (IllegalStateException e) {
                // Log.e(TAG, e.getLocalizedMessage(), e);

            } catch (IOException e) {
                // Log.e(TAG, e.getLocalizedMessage(), e);
            }

        }

    }catch(NullPointerException ne){


    }
}
catch(Exception e) {
    e.printStackTrace();

}

//Log.v("@WebSErvice:", "REsult" + result);

3 个答案:

答案 0 :(得分:1)

之前我已经完成了此操作,我已经跟踪了最高可达80mb的内容,并使用MultiPartEntity尝试上传功能。

public class asyncUploadtrack extends AsyncTask<Void, Integer, Void>
    {
        HttpResponse response;
        private android.app.ProgressDialog dialog;
        long totalSize;

        protected void onPostExecute(String result)
        {

        }
        @Override
        protected void onPreExecute() 
        {

        }
        @Override
        protected void onProgressUpdate(Integer... values)
        {

        }
        protected Void doInBackground(Void... params)
        {
            Log.i("Do in Backgtound", "Background");
            String url =app.WEB_API_URL+"?op="+ Constant.METHOD_UPLOAD_TRACK;
            File video = new File(trackPath); // path of file 
            Bitmap out = Constant.bitmapResize(TrackFragment.btmTrackImg,308, 296) ;//Bitmap.createScaledBitmap(TrackFragment.btmTrackImg, 408, 396,true);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            out.compress(CompressFormat.JPEG, 50, bos);
            byte[] data = bos.toByteArray();


            HttpClient httpclient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);




             try 
            {
                MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                multipartEntity.addPart("music", new FileBody(video));
                multipartEntity.addPart("title",new StringBody(trackTitle));
                multipartEntity.addPart("user", new StringBody(app.preferences.getStringPref("userId")));


                multipartEntity.addPart("filename", new StringBody("song.mp3"));
                multipartEntity.addPart("avatar",new ByteArrayBody(data, "trackImage"));
                //After adding everything we get the content's lenght
                totalSize = multipartEntity.getContentLength();
                post.setEntity(multipartEntity);
                response = httpclient.execute(post);
                try 
                {
                    Log.i("Response is",response.getStatusLine().toString());
                                    } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
            return null;
        }
    }

答案 1 :(得分:0)

检查此代码会对您有所帮助。

public int uploadFile(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 :"+imagepath);

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

           return 0;

      }
      else
      {
           try {

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);

               // Open a HTTP  connection to  the URL
               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);
               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);

               // Responses from the server (code and message)
               serverResponseCode = conn.getResponseCode();
               String serverResponseMessage = conn.getResponseMessage();

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

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                  +" F:/wamp/wamp/www/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 (Exception e) {

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

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      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;

       } // End else block
     }

同时检查此链接。 http://sunil-android.blogspot.in/2013/09/file-upload-on-php-server-in-android.html

祝你好运。

答案 2 :(得分:0)

Video Uploading not working in YII 这个链接帮助了我..代码中没有错误。这是服务器端的问题。