2013-01-24 24 views
0

我有一个应用程序在Android女巫拍摄一张照片,需要将其uppad到服务器与PHP。发送数据从Java(Android)到PHP与POST

起初没有问题,我能够上传它,但现在我需要传递图片上传到服务器的路径。当我尝试发送两个值时会出现问题。

我使用下面的代码:

private void httpPostFileUpload(String fpath, String uPath){ 
     HttpURLConnection connection = null; 
     DataOutputStream outputStream = null; 
     DataInputStream inputStream = null; 

     //Path where to upload 
     String uploadPath = uPath; 

     String pathToOurFile = fpath; 
     Log.v("file path",fpath.toString()); 
     String urlServer = "http://leojg.alwaysdata.net/tests/androidConnect/handle_upload.php"; 

     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 
     String fname = ""; 

     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 1*1024*1024; 

     try 
     { 
      File f = new File(pathToOurFile); 
      fname = f.getName(); 

      FileInputStream fileInputStream = new FileInputStream(f); 

      URL url = new URL(urlServer); 
      connection = (HttpURLConnection) url.openConnection(); 

      // Allow Inputs & Outputs 
      connection.setDoInput(true); 
      connection.setDoOutput(true); 
      connection.setUseCaches(false); 

      // Enable POST method 
      connection.setRequestMethod("POST"); 

      connection.setRequestProperty("Connection", "Keep-Alive"); 
      connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); 

      outputStream = new DataOutputStream(connection.getOutputStream()); 
      outputStream.writeBytes(twoHyphens + boundary + lineEnd); 

      Log.d("path file", pathToOurFile); 
      Log.d("path up", uploadPath); 

     outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd); 
      outputStream.writeBytes(lineEnd); 

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

      // Read file 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

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

      outputStream.writeBytes(lineEnd); 
      outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

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

      Log.d("amanda", "upload async finished, server response : " + serverResponseMessage); 

      fileInputStream.close(); 
      fileInputStream = null; 
      outputStream.flush(); 
      outputStream.close(); 
      outputStream = null; 
      f= null; 



      parent.invokeJs("pictureUploadEnded('" + fname + "')"); 
      this.delete(fpath); 

     } 
      catch (Exception ex) 
     { 
       Log.d("amanda", "exception uploading image : " + ex.getMessage()); 
     }  
} 

我敢肯定,这个问题是在这条线

outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd); 

这是一个使后车身。我不知道在哪里attrach uploadPath

+1

和问题是什么 – Ibu

+0

我如何发送两个或更多的POST值。 –

+0

看看... http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk –

回答

0

请检查该link

本例中使用的HttpClient和HttpPost类,以简化使用POST方法将数据发送到服务器并得到响应返回。

1

对我来说好了下面的类工作:

import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import org.json.JSONException; 
import org.json.JSONObject; 
import org.json.JSONTokener; 
import android.os.Environment; 
import android.util.Log; 

public class HttpPictureUpload implements Runnable { 
private String TAG = "HTTPFILEUPLOAD"; 
private URL connectURL; 
private FileInputStream fileInputStream = null; 
private String pictureFileName; 
private String myName; 

public HttpPictureUpload(String urlString, String pictureFileNameString, 
     String myNameString) { 
    try { 
     connectURL = new URL(urlString); 

     pictureFileName = pictureFileNameString; 
     myName = myNameString; 

    } catch (Exception ex) { 
     Log.i(TAG, "URL Malformatted"); 
    } 
} 

public void SendPictureNow() { 

    Sending(); 
} 

private void Sending() { 
    int maxBufferSize = 1 * 1024*1024*1024; 
    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 

    try { 

     fileInputStream = new FileInputStream(Environment 
       .getExternalStorageDirectory().toString() 
       + "/Picture/" 
       + pictureFileName); 

     Log.e(TAG, "Starting Http File Sending to URL"); 

     // Open a HTTP connection to the URL 
     HttpURLConnection conn = (HttpURLConnection) connectURL 
       .openConnection(); 
     conn.setChunkedStreamingMode(maxBufferSize); 
     // conn.setchu 

     // Allow Inputs 
     conn.setDoInput(true); 

     // Allow Outputs 
     conn.setDoOutput(true); 

     // Don't use a cached copy. 
     conn.setUseCaches(false); 

     // Use a post method. 
     conn.setRequestMethod("POST"); 

     conn.setRequestProperty("Connection", "Keep-Alive"); 

     conn.setRequestProperty("Content-Type", 
       "multipart/form-data;boundary=" + boundary); 

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

     // sending appid 
     dos.writeBytes(twoHyphens + boundary + lineEnd); 
     dos.writeBytes("Content-Disposition: form-data; name=\"my_name\"" 
       + lineEnd); 
     dos.writeBytes(lineEnd); 
     dos.writeBytes(myName); 
     dos.writeBytes(lineEnd); 
     dos.writeBytes(twoHyphens + boundary + lineEnd); 


     dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" 
       + System.currentTimeMillis() + "\"" + lineEnd); 
     dos.writeBytes(lineEnd); 

     int bytesAvailable = fileInputStream.available(); 

     byte[] buffer = new byte[bytesAvailable]; 

     int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable); 

     while (bytesRead > 0) { 
      dos.write(buffer, 0, bytesAvailable); 
      bytesAvailable = fileInputStream.available(); 
      bytesAvailable = Math.min(bytesAvailable, maxBufferSize); 
      bytesRead = fileInputStream.read(buffer, 0, bytesAvailable); 
     } 
     dos.writeBytes(lineEnd); 
     dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

     fileInputStream.close(); 

     dos.flush(); 

     Log.e(TAG, 
       "File Sent, Response: " 
         + String.valueOf(conn.getResponseCode())); 

     InputStream is = conn.getInputStream(); 

     // retrieve the response from server 
     int ch; 

     StringBuffer b = new StringBuffer(); 

     while ((ch = is.read()) != -1) { 
      b.append((char) ch); 

     } 

     String s = b.toString(); 

     Log.i("Response", s); 
     dos.close(); 
    } catch (MalformedURLException ex) { 
     Log.e(TAG, "URL error: " + ex.getMessage(), ex); 
    } 

    catch (IOException ioe) { 
     Log.e(TAG, "IO error: " + ioe.getMessage(), ioe); 
    } 
} 

@Override 
public void run() { 
    // TODO Auto-generated method stub 
} 
} 

上面的类可以用来发送图片文件或任何其他文件和一个任意字符串。
要使用上面:

HttpPictureUpload uploadPicture=new HttpPictureUpload("http://serverurl.com/webservice.php", "tux.png", "my name is john"); 
uploadPicture.SendPictureNow();