Android: Uploading a file to a page along with other POST strings

前端 未结 1 788
广开言路
广开言路 2021-01-13 09:47

I am trying to upload an image to a PHP page along with some other info about the image so the PHP page knows what to do with it. Currently, I am getting away with it using

相关标签:
1条回答
  • 2021-01-13 10:35

    You can try an take a look at the answer I added for this similar question: https://stackoverflow.com/a/9003674/472747

    Here is the code:

    byte[] data = {10,10,10,10,10}; // better get this from a file or memory
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost("server url");
    ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("image", bab);
    
    FormBodyPart bodyPart=new FormBodyPart("formVariableName", new StringBody("formValiableValue"));
    reqEntity.addPart(bodyPart);
    bodyPart=new FormBodyPart("formVariableName2", new StringBody("formValiableValue2"));
    reqEntity.addPart(bodyPart);
    bodyPart=new FormBodyPart("formVariableName3", new StringBody("formValiableValue3"));
    reqEntity.addPart(bodyPart); 
    postRequest.setEntity(reqEntity);
    HttpResponse response = httpClient.execute(postRequest);
    BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = null;
    while((line = in.readLine()) != null) {
        System.out.println(line);
    }
    
    0 讨论(0)
提交回复
热议问题