android httpclient 上傳圖片

須要依賴  httpmime.jar post

/**
 * 上傳圖片
 * 
 * @param url
 *            上傳地址
 * @param filepath
 *            圖片路徑
 * @return
 */
public String uploadImage(String url, String filepath) {
    File file = new File(filepath);

    if (!file.exists()) {
        Log.i("leslie", "file not exists");
        return null;
    }

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

    FileBody fileBody = new FileBody(file, "image/jpeg");
    MultipartEntity entity = new MultipartEntity();
    // image 是服務端讀取文件的 key
    entity.addPart("image", fileBody);

    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        String result = EntityUtils.toString(response.getEntity(), "utf-8");

        if (statusCode == 201) {
            // upload success
            // do something
        }

        return result;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}
相關文章
相關標籤/搜索