2011-02-23 82 views
2

你好,我想上傳圖像從Android模擬器到asp.net服務器。下面的代碼可以與服務器通信。當我試圖創建一個文本文件來查看從android發送的數據是否成功。但沒有文件數據沒有發送到服務器。我試圖發送純文本到服務器,但我在服務器上創建的文件沒有打印文本。Android的圖像上傳問題

這裏的代碼: HttpURLConnection conn = null;

String boundary = "=============="; 

     try 
     { 
      String disposition = "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + filename + ".jpg\""; 
      String contentType = "Content-Type: application/octet-stream"; 

      String t1 = "Content-Disposition: form-data; name=\"test\";"; 
      String t2 = "Content-Type: text/plain"; 

      // This is the standard format for a multipart request 
      StringBuffer requestBody = new StringBuffer(); 
      /* 
      requestBody.append("--"+boundary); 
      requestBody.append('\n'); 
      requestBody.append(disposition); 
      requestBody.append('\n'); 
      requestBody.append(contentType); 
      requestBody.append('\n'); 
      requestBody.append('\n'); 
      requestBody.append(new String(getByteFromStream(stream))); 
      */ 

      requestBody.append('\n'); 
      requestBody.append('\n'); 
      requestBody.append("--"+boundary); 
      requestBody.append('\n'); 
      requestBody.append(t1); 
      requestBody.append('\n'); 
      requestBody.append(t2); 
      requestBody.append('\n'); 
      requestBody.append('\n'); 
      requestBody.append("basdfsdafsadfsad"); 
      requestBody.append("--"+boundary+"--"); 

      // Make a connect to the server 
      URL url = new URL(targetURL); 
      conn = (HttpURLConnection) url.openConnection(); 

      // Put the authentication details in the request 
      /* 
      if (username != null) { 

       String usernamePassword = username + ":" + password; 
       String encodedUsernamePassword = Base64.encodeBytes(usernamePassword.getBytes()); 
       conn.setRequestProperty ("Authorization", "Basic " + encodedUsernamePassword); 
      } 
      */ 
      conn.setDoOutput(true); 
      conn.setDoInput(true); 
      conn.setUseCaches(false); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("MIME-Version:", "1.0"); 
      conn.setRequestProperty("Content-Type", "multipart/mixed; boundary=" + boundary); 

      // Send the body 
      DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream()); 
      dataOS.writeBytes(requestBody.toString()); 
      dataOS.flush(); 
      dataOS.close(); 

      // Ensure we got the HTTP 200 response code 
      int responseCode = conn.getResponseCode(); 
      if (responseCode != 200) { 
       throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url)); 
      } 

我的請求正文佈局不正確嗎?

+0

如果可能的話,你爲什麼不看原始請求你r服務器? – xandy 2011-02-23 00:27:19

+0

請教我如何查看服務器上的原始數據 – LittleFunny 2011-02-23 01:50:38

回答

8

我使用asp.net作爲文件處理程序。下面是你將使用到該文件

String pathToOurFile = "/mnt/sdcard/sysdroid.png";//this will be the file path  String urlServer = "http://yourdomain/fileupload.aspx"; 
int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1*1024*1024; 

    try 
    { 
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); 

    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"); 
    connection.setRequestProperty("SD-FileName", "sysdroid.png");//This will be the file name 

    outputStream = new DataOutputStream(connection.getOutputStream()); 
    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); 
    } 

    int serverResponseCode = connection.getResponseCode(); 
    String serverResponseMessage = connection.getResponseMessage(); 
    Log.d("ServerCode",""+serverResponseCode); 
    Log.d("serverResponseMessage",""+serverResponseMessage); 
    fileInputStream.close(); 
    outputStream.flush(); 
    outputStream.close(); 


} 
    catch (Exception ex) 
    { 
     //ex.printStackTrace(); 
     Log.e("Error: ", ex.getMessage()); 
    } 

到目前爲止好上傳該事件的簡單的Android代碼。讓我們看看asp.net代碼。我爲此使用了簡單的「Web Form」。後面的代碼是

protected void Page_Load(object sender, EventArgs e) 
{ 
    string uploadDir = Server.MapPath("~/images"); 
    string imgPath = Path.Combine(uploadDir, Request.Headers["SD-FileName"]); 

    try{   
     byte[]bytes = new byte[Request.InputStream.Length]; 
     Request.InputStream.Read(bytes, 0, bytes.Length); 
     System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes); 
     Bitmap btMap = (Bitmap)System.Drawing.Image.FromStream(ms); 
     btMap.Save(imgPath, ImageFormat.Jpeg); 
     ms.Close(); 
    } 
    catch (Exception exp) 
    {    
     Response.Write(exp.Message); 
    }  
} 

希望這會工作,你有Android和SD卡和asp.net文件夾的讀/寫權限的知識。

歡呼 Fahar

0

因爲您上傳兩個文件,所以你應該看最後的格式。祝你好運。 6.例子

假設服務器提供了以下HTML:

<FORM ACTION="http://server.dom/cgi/handle" 
     ENCTYPE="multipart/form-data" 
     METHOD=POST> 
What is your name? <INPUT TYPE=TEXT NAME=submitter> 
What files are you sending? <INPUT TYPE=FILE NAME=pics> 
</FORM> 

,並在用戶鍵入「喬吹」的名稱字段,並選擇一個文本文件 「FILE1.TXT」的答案到'你要發送什麼文件?'

客戶端可能會發送回以下數據:如果用戶也表示了答案 圖像文件「file2.gif」到「什麼文件你發送」

Content-type: multipart/form-data, boundary=AaB03x 

    --AaB03x 
    content-disposition: form-data; name="field1" 

    Joe Blow 
    --AaB03x 
    content-disposition: form-data; name="pics"; filename="file1.txt" 
    Content-Type: text/plain 

    ... contents of file1.txt ... 
    --AaB03x-- 

,客戶端可能客戶端可能會發送回 以下數據:

Content-type: multipart/form-data, boundary=AaB03x 

    --AaB03x 
    content-disposition: form-data; name="field1" 

    Joe Blow 
    --AaB03x 
    content-disposition: form-data; name="pics" 
    Content-type: multipart/mixed, boundary=BbC04y 

    --BbC04y 
    Content-disposition: attachment; filename="file1.txt" 
    Content-Type: text/plain 

    ... contents of file1.txt ... 
    --BbC04y 
    Content-disposition: attachment; filename="file2.gif" 
    Content-type: image/gif 
    Content-Transfer-Encoding: binary 

     ...contents of file2.gif... 
    --BbC04y-- 
    --AaB03x-- 

Form-based File Upload in HTML