2011-03-24 96 views
12

我试图将图像上传到服务器以及从表单收集的一些JSON数据。在Multipart中将图像上传到服务器以及Android中的JSON数据

服务器有认证。

METHOD: post 

HEADERS: 

Authorization Basic d2Vic2VydmljZTpyM05hdTE3Rw== 

Content-Type multipart/form-data;boundary=xxxxxxxx 

BODY: 

--xxxxxxxx 

Content-Disposition: form-data; name="jsonFile" 
Content-Type: application/json 

{"model":"Premium","deviceLongitude":4.79337638,"pseudo":"nickname","deviceLatitude":45.7671507,"year":"2005","email":"[email protected]","deviceLocale":"fr_FR","title":"my picture"} 

--xxxxxxxx 

Content-Disposition: form-data; name="imgName" 
Content-Type: image/jpeg 

//Image data array 

/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAAB 
AAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAB4KAD 
AAQAAAABAAACgAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB 
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEB 
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB 
AQEBAQEBAQH/wAARCAKAAeADAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAA 
AAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF 
--xxxxxxxx 

回答

4
/** 
* This utility function will upload the file to the Url 
* * @param filePath - absolute path of the file to be uploaded 
* @param postUrl - Remote Url where the file need to be posted 
* @param contentType - content-type of the uploaded file 
* @throws Exception 
*/ 
public static void postFile(String filePath, String postUrl, 
     String pictureTitleStr, String pseudoTextStr) 
     throws Exception { 

    String url = postUrl; 
    HttpURLConnection conn = null; 
    final String CrLf = "\r\n"; 
    JSONObject json = new JSONObject(); 
    int bytesRead = 0; 


    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "xxxxxxxx"; 
    String EndBoundary = ""; 
    int maxBufferSize = 1 * 1024 * 1024; 

    HttpResponse response = null; 

    // Having HttpClient to respond to both HTTP and HTTPS url connection by accepting the urls along with keystore/trust certificates 

    try { 
     KeyStore trustStore = KeyStore.getInstance(KeyStore 
       .getDefaultType()); 
     trustStore.load(null, null); 

     SSLSocketFactory sf = new MySSLSocketFactory(trustStore); 
     sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 
     HttpParams params = new BasicHttpParams(); 
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 
     HttpProtocolParams.setUserAgent(params, "YourAppName/1.1"); 
     HttpConnectionParams.setStaleCheckingEnabled(params, false); 
     HttpConnectionParams.setConnectionTimeout(params, 20 * 1000); 
     HttpConnectionParams.setSoTimeout(params, 20 * 1000); 
     HttpConnectionParams.setSocketBufferSize(params, 8192); 
     HttpClientParams.setRedirecting(params, false); 

     SchemeRegistry registry = new SchemeRegistry(); 
     registry.register(new Scheme("http", PlainSocketFactory 
       .getSocketFactory(), 80)); 
     registry.register(new Scheme("https", sf, 443)); 

     ClientConnectionManager ccm = new ThreadSafeClientConnManager(
       params, registry); 

     mHttpClient = new DefaultHttpClient(ccm, params); 



    } catch (Exception e) { 

    } 

    String base64EncodedCredentials = Base64.encodeToString((userName + ":" + password).getBytes("US-ASCII"), 
      Base64.DEFAULT); 
    System.out.println("Encoded Credit " + base64EncodedCredentials); 

      json.put("pseudo", pseudoTextStr); 
      json.put("title", pictureTitleStr); 

      String jsonStr = json.toString(); 
// System.out.println("JSON VALUE " + jsonStr); 

    URL url2 = new URL(postUrl); 



    Bitmap bm = BitmapFactory.decodeFile(filePath); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    bm.compress(Bitmap.CompressFormat.JPEG, 25, baos); // bm is the bitmap object 
    byte[] b = baos.toByteArray(); 

    String encodedImage = Base64.encodeToString(b, Base64.DEFAULT); 


    String str = twoHyphens + boundary + lineEnd; 
    String str2 = "Content-Disposition: form-data; name=\"jsonFile\""; 
    String str3 = "Content-Type: application/json"; 
    String str4 = "Content-Disposition: form-data; name=\"imgName\""; 
    String str5 = "Content-Type: image/jpeg"; 
    String str6 = twoHyphens + boundary + twoHyphens; 



    String StrTotal = str + str2 + "\r\n" + str3 + "\r\n" +"\r\n" + jsonStr + "\r\n" + str 
      + str4 + "\r\n" + str5 + "\r\n"+"\r\n"+ encodedImage + "\r\n" + str6; 

    //System.out.print("Multipart request string is "+StrTotal); 

HttpPost post = new HttpPost(postUrl); 


post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(
       userName, password), "UTF-8", false)); 
post.addHeader("Content-Type","multipart/form-data;boundary="+boundary); 
// System.out.println("Sending Post proxy request: " + post); 

StringEntity se = new StringEntity(StrTotal); 
se.setContentEncoding("UTF-8"); 
post.setEntity(se); 
response = mHttpClient.execute(post); 

/* Checking response */ 

statusCode = response.getStatusLine().getStatusCode(); 
System.out.println("Http Execute finish " + statusCode); 

HttpEntity entity = response.getEntity(); 
String getResponseText = entity.toString(); // EntityUtils.toString(entity); 
System.out.println(" Post Response Text from Server : " 
     + getResponseText); 



} 
+0

谢谢你的答案,它帮助我解决了我的问题。同时,你可以帮我张贴多个图像与json一起。我在这里发布了一个问题,请看看: http://stackoverflow.com/questions/40279640/send-json-multiple-images-as-multipart-form-data-using-httpurlconnection-andro?noredirect=1 #comment67819025_40279640 – 2016-10-27 09:13:25

4

最后一行应--xxxxxxxx--,而不是--xxxxxxxx

+0

Hello Bert,这是正确的,但有没有解决方案或更新如何可以在Android中完成? – ReachmeDroid 2011-05-16 12:04:20

2
public static boolean uploadImage(final byte[] imageData, String filename ,String message) throws Exception{ 

    String responseString = null;  

    PostMethod method; 

    String auth_token = Preference.getAuthToken(mContext); 


    method = new PostMethod("http://10.0.2.20/"+ "upload_image/" +Config.getApiVersion() 
      + "/"  +auth_token); 

      org.apache.commons.httpclient.HttpClient client = new    
             org.apache.commons.httpclient.HttpClient(); 
      client.getHttpConnectionManager().getParams().setConnectionTimeout(
          100000); 

      FilePart photo = new FilePart("icon", 
                new ByteArrayPartSource(filename, imageData)); 

      photo.setContentType("image/png"); 
      photo.setCharSet(null); 
      String s = new String(imageData); 
      Part[] parts = { 
          new StringPart("message_text", message), 
          new StringPart("template_id","1"), 
          photo 
          }; 

      method.setRequestEntity(new 
              MultipartRequestEntity(parts,  method.getParams())); 
      client.executeMethod(method); 
      responseString = method.getResponseBodyAsString(); 
      method.releaseConnection(); 

      Log.e("httpPost", "Response status: " + responseString); 

    if (responseString.equals("SUCCESS")) { 
      return true; 
    } else { 
      return false; 
    } 
} 

您还可以看到在我的博客为例Here

3

我知道这个帖子是一对夫妇岁,但我想从here可共享使用MultiPartEntity我的解决方案的一部分HttpClient下载。我使用的是4.2.5版本。

我原来使用了一个类似于上面的过程,它运行良好,直到我开始支持上传视频时出现内存错误。我在这里研究了很多帖子,并得到了很多好主意。我使用Java反编译器available here来查看Jar文件中的代码,以了解如何将事物放在一起。

//filepath is passed in like /mnt/sdcard/DCIM/100MEDIA/VIDEO0223.mp4  
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); 

String extension = fileName.substring(fileName.lastIndexOf(".") + 1); 

String json = "{your_json_goes_here}"; 

File media = new File(filePath); 

URI uri = your_uri_goes_here; 

DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpPost post = new HttpPost(uri); 

StringBody jsonBody = new StringBody(json, "application/json", null); 

FormBodyPart jsonBodyPart = new FormBodyPart("json", jsonBody); 

String mimeType; 

if (requestCode == Constants.ACTION_TAKE_VIDEO) { 
    mimeType = "video/" + extension; 
} else { 
    // default to picture 
    mimeType = "image/" + extension; 
} 

FileBody fileBody = new FileBody(media, mimeType, "ISO-8859-1"); 

FormBodyPart fileBodyPart = new FormBodyPart(fileName, fileBody);    

MultipartEntity mpEntity = new MultipartEntity(null, "xxBOUNDARYxx", null); 

mpEntity.addPart(jsonBodyPart); 
mpEntity.addPart(fileBodyPart); 

post.addHeader("Content-Type", "multipart/mixed;boundary=xxBOUNDARYxx"); 

post.setEntity(mpEntity); 

HttpResponse response = httpClient.execute(post); 

InputStream data = response.getEntity().getContent(); 
BufferedReader bufferedReader = new BufferedReader(
     new InputStreamReader(data)); 
String responseLine; 
StringBuilder responseBuilder = new StringBuilder(); 

while ((responseLine = bufferedReader.readLine()) != null) { 
    responseBuilder.append(responseLine); 
} 

System.out.println("Response: " + responseBuilder.toString()); 
+0

我没有明确指定边界和内容类型。然后使用“multipart/form-data”生成头文件,所有部分都有各自的内容类型(在我的例子中是json和octet-stream)。 “多部分/混合”是否对您更好? – Risadinha 2013-08-28 17:40:11

0

试试这个代码很容易

public String postAsync(String url, String action, JSONObject jsonObject, String fileUri) throws JSONException { 
 
     String result = ""; 
 
     try { 
 
      HttpClient httpClient = new DefaultHttpClient(); 
 
      HttpPost httpPost = new HttpPost(url); 
 
      MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); 
 
      entityBuilder.setMode(HttpMultipartMode.STRICT); 
 
      File file = new File(fileUri); 
 
      entityBuilder.addPart("file", new FileBody(file)); 
 
      entityBuilder.addTextBody(DMConstant.ACTION_JSON, action); 
 
      entityBuilder.addTextBody(DMConstant.DATA_JSON, jsonObject.toString(), ContentType.create("application/json", Consts.UTF_8)); 
 
      HttpEntity entity = entityBuilder.build(); 
 
      httpPost.setEntity(entity); 
 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
 
      InputStream inputStream = httpResponse.getEntity().getContent(); 
 
      if (inputStream != null) { 
 
       result = dmUtils.convertStreamToString(inputStream); 
 
      } else { 
 
       Log.i("Input Stream is Null", "Input Stream is Null"); 
 
      } 
 
     } catch (UnsupportedEncodingException e) { 
 
      Log.e("Unsupported Encoding", e.getMessage()); 
 
     } catch (ClientProtocolException e) { 
 
      Log.e("Client Protocol", e.getMessage()); 
 
     } catch (IOException e) { 
 
      Log.e("IOException", e.getMessage()); 
 
     } 
 
     Log.i("JSON Object as Response", result); 
 
     return result; 
 
    }

........ 
 

 
JSONObject urlObject = new JSONObject(); 
 
         urlObject.put("userName", "user name"); 
 
         urlObject.put("email_id", "ä[email protected]"); 
 
         urlObject.put("user_pass", "123456"); 
 

 

 
postAsync(URL, "php function name", urlObject, imageFile);

0

这是使用上传图像和JSONArray为例MultipartE ntity-lib:org.apache.http.entity.mime

List <Entity> students = getStudentList(); 

    MultipartEntity studentList = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

    for(int i=0; i<students.size();i++){ 

     try { 
      studentList.addPart("studentList[][name]", new StringBody(String.valueOf(students.get(i).getName()))); 
      studentList.addPart("studentList[][addmission_no]", new StringBody(String.valueOf(students.get(i).getAddmissionNo))); 
      studentList.addPart("studentList[][gender]", new StringBody(String.valueOf(students.get(i).getGender))); 

      File photoImg = new File(students.get(i).getImagePath()); 
      studentList.addPart("studentList[][photo]",new FileBody(photoImg,"image/jpeg")); 


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

    HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost(URL); 

    post.addHeader("X-Auth-Token", mUserToken); 
    post.setEntity(studentList); 

    org.apache.http.HttpResponse response = null; 
    try { 
     response = client.execute(post); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    HttpEntity httpEntity = response.getEntity(); 
    JSONObject myObject; 
    try { 
     String result = EntityUtils.toString(httpEntity); 
     // do your work 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
相关问题