上传文件不显示任何错误,但不上传文件

时间:2014-08-18 15:01:03

标签: android file-upload http-post multipartentity

我正在尝试使用多种方法将视频文件从Android手机上传到服务器。他们似乎都没有像现在一样工作。

首先,我尝试使用正常的多部分上传,我上传图像并运行良好。

代码段

public int uploadFileVideo(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();         
         runOnUiThread(new Runnable() {
             public void run() {
                Toast.makeText(GcmActivity.this, "File not found", Toast.LENGTH_LONG).show();
             }
         });

         return 0;

    }
    else
    {
         try {                 
               // open a URL connection to the Servlet
             FileInputStream fileInputStream = new FileInputStream(sourceFile);
             URL url = new URL("http://example.com/ccs-business/upload.php");
             conn = (HttpURLConnection) url.openConnection();
             conn.setDoInput(true); 
             conn.setDoOutput(true); 
             conn.setChunkedStreamingMode(0);
             conn.setUseCaches(false); 
             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_video", 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("Content-Disposition: form-data; name=\"uploaded_video\";filename=\"" + fileName +"\"" + lineEnd);
             dos.writeBytes(lineEnd);
             bytesAvailable = fileInputStream.available();

            /* bufferSize = Math.min(bytesAvailable, maxBufferSize);
             buffer = new byte[bufferSize];
             bytesRead = fileInputStream.read(buffer, 0, bufferSize); */



             //bufferSize = Math.min(bytesAvailable, maxBufferSize);
             //buffer = new byte[bufferSize];
             //byte byt[]=new byte[bufferSize];

             byte[] buf = new byte[ 4096 ];
             int read = 0;
             while( ( read = fileInputStream.read( buf ) ) != -1 ) {
                 dos.write( buf, 0, read );
             }




             // 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() {                             

                          Toast.makeText(GcmActivity.this, "File Upload Complete.",
                                       Toast.LENGTH_SHORT).show();
                          dialog.dismiss();
                      }
                  });               
             }   
             fileInputStream.close();
             dos.flush();
             dos.close();

        } catch (MalformedURLException ex) {

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

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(GcmActivity.this, "MalformedURLException",
                                                        Toast.LENGTH_SHORT).show();
                }
            });

            Log.v("ONMESSAGE", "error: " + ex.getMessage(), ex); 
        } catch (Exception e) {

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

            runOnUiThread(new Runnable() {
                public void run() {

                    Toast.makeText(GcmActivity.this, "This file can not be uploaded ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.v("ONMESSAGE", "Exception : " + e.getMessage(), e); 
        }
        dialog.dismiss();      
        return serverResponseCode;

     } // End else block
   }

它不起作用,所以我尝试了下一个程序

代码段

 public void uploadWithHttpClient(String uri)
 {
  File myFile = new File(uri);

  try{
      AsyncHttpClient client = new AsyncHttpClient();
      RequestParams params = new RequestParams();        
      params.put("uploaded_video", myFile);       
      client.post(this, "http://example.com/ccs-business/upload.php", params, new AsyncHttpResponseHandler() {
          @Override
          public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { 
              dialog.dismiss();
              Log.v("ONMESSAGE", "Success");
          }

          @Override
          public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
              Log.v("ONMESSAGE", "Failure");
              dialog.dismiss();
          }
      });

  }
  catch(Exception e)
  {
      dialog.dismiss();
      Log.v("ONMESSAGE", "Exception is " + e.toString());
  }


  }

然后我写了一个扩展 MultipartEntity 的类然后在我尝试上传的AsyncTask中。有些文件上传,有些则没有。

代码段

public class CustomMultiPartEntity extends MultipartEntity
{

private final ProgressListener listener;

public CustomMultiPartEntity(final ProgressListener listener)
{
    super();
    this.listener = listener;
}

public CustomMultiPartEntity(final HttpMultipartMode mode, final ProgressListener listener)
{
    super(mode);
    this.listener = listener;
}

public CustomMultiPartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener)
{
    super(mode, boundary, charset);
    this.listener = listener;
}

@Override
public void writeTo(final OutputStream outstream) throws IOException
{
    super.writeTo(new CountingOutputStream(outstream, this.listener));
}

public static interface ProgressListener
{
    void transferred(long num);
}

public static class CountingOutputStream extends FilterOutputStream
{

    private final ProgressListener listener;
    private long transferred;

    public CountingOutputStream(final OutputStream out, final ProgressListener listener)
    {
        super(out);
        this.listener = listener;
        this.transferred = 0;
    }

    public void write(byte[] b, int off, int len) throws IOException
    {
        out.write(b, off, len);
        this.transferred += len;
        this.listener.transferred(this.transferred);
    }

    public void write(int b) throws IOException
    {
        out.write(b);
        this.transferred++;
        this.listener.transferred(this.transferred);
    }
}
}

AysncTask CLass

private class HttpMultipartPost extends AsyncTask<String, Integer, String>
    {
        ProgressDialog pd;
        long totalSize;

        @Override
        protected void onPreExecute()
        {
            pd = new ProgressDialog(GcmActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.setMessage("Uploading Video...");
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        protected String doInBackground(String... arg0)
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost("http://example.com/ccs-business/upload.php");

            try
            {
                CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new ProgressListener()
                {
                    @Override
                    public void transferred(long num)
                    {
                        publishProgress((int) ((num / (float) totalSize) * 100));
                    }
                });

                // We use FileBody to transfer an image
                multipartContent.addPart("uploaded_video", new FileBody(new File(pathOfpictoUpload)));
                //multipartContent.addPart(name, contentBody)d
                totalSize = multipartContent.getContentLength();

                // Send it
                httpPost.setEntity(multipartContent);
                HttpResponse response = httpClient.execute(httpPost, httpContext);
                String serverResponse = EntityUtils.toString(response.getEntity());


                return serverResponse;
            }

            catch (Exception e)
            {
                System.out.println(e);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress)
        {
            pd.setProgress((int) (progress[0]));
        }

        @Override
        protected void onPostExecute(String ui)
        {
            pd.dismiss();
            Log.v("ONMESSAGE", "SERVER RESPONSE IS " + ui);
        }
    }   

0 个答案:

没有答案