Upload a image through an HTTP form, via MultipartEntity (how to change media type from application to image)

狂风中的少年 提交于 2020-01-01 22:16:24

问题


Here is my code

            HttpClient httpClient = new DefaultHttpClient();           
            HttpPost httpPost = new HttpPost("http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?");
            File file = new File("/mnt/sdcard/xperia.png");
            FileBody fileBody = new FileBody(file);
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("post_id", new StringBody("906"));
            reqEntity.addPart("user_id", new StringBody("1"));
            reqEntity.addPart("files", fileBody);
            httpPost.setEntity(reqEntity);                                      
            response = httpClient.execute(httpPost);                 
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            response_string =convertStreamToString(is);



            ..........

method to parse response

    private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append((line + "\n"));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

I m getting success from the server, but image is not received on server ... wht i m doing wrong


回答1:


Apply this


private String doFileUpload() {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    myimage.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] imagebyte = stream.toByteArray();

    System.out.println(imagebyte + "...................................");


    String urlString = "your url";

    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(urlString);
        MultipartEntity reqEntity = new MultipartEntity();

        Calendar cal = Calendar.getInstance();
        String image_name = cal.getTime().toString();
        image_name = image_name.replace(" ", "");
        image_name = image_name.replace(":", "");
        image_name = image_name.substring(3, 14);

        //userfile
        reqEntity.addPart("featured_img", new ByteArrayBody(imagebyte,
                "Chasin_" + image_name + "_image.jpg"));




        reqEntity.addPart("title", new StringBody(title_var));
        reqEntity.addPart("description",new StringBody(description_var));
        reqEntity.addPart("category",new StringBody(cat_var));
        reqEntity.addPart("tags",new StringBody(tag));

        reqEntity.addPart("userid",new StringBody(Constants.USER_ID));


        post.setEntity(reqEntity);

        HttpResponse response = client.execute(post);
         HttpEntity resEntity = response.getEntity();
         response_str = EntityUtils.toString(resEntity);




    } catch (Exception ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    }
    return response_str;
}



回答2:


Guys i think i have to work on these things

public void connectForMultipart() throws Exception {
    con = (HttpURLConnection) ( new URL(url)).openConnection();
    con.setRequestMethod("POST");
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setRequestProperty("Connection", "Keep-Alive");
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    con.connect();
    os = con.getOutputStream();
}

public void addFormPart(String paramName, String value) throws Exception {
    writeParamData(paramName, value);
}

public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
    os.write( (delimiter + boundary + "\r\n").getBytes());
    os.write( ("Content-Disposition: form-data; name=\"" + paramName +  "\"; filename=\"" + fileName + "\"\r\n"  ).getBytes());
    os.write( ("Content-Type: application/octet-stream\r\n"  ).getBytes());
    os.write( ("Content-Transfer-Encoding: binary\r\n"  ).getBytes());
    os.write("\r\n".getBytes());

    os.write(data);

    os.write("\r\n".getBytes());
}   
public void finishMultipart() throws Exception {
    os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}

I have changed Content-Type: application/octet-stream\r\n" to Content-Type: image/jpeg\r\n\r\n and it worked :)




回答3:


File imgFile = new File(Environment.getExternalStorageDirectory() + "/photo1/image2.jpg");

if (imgFile.exists()) {
    myimage = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    // im.setImageBitmap(myimage);
}


来源:https://stackoverflow.com/questions/22933853/upload-a-image-through-an-http-form-via-multipartentity-how-to-change-media-ty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!