Android上传图片和文字到服务器

1. 首先到Appache官网下载第三方jar包httpmime(可以到这里下载http://download.csdn.net/detail/likesidehu/9651525,这个jar包配合下面代码验证没问题)

2. 服务器地址: http://localhost:8080/xxx/xxx/xxx

3. 本地图片地址/sdcard/Pictures/abc.png

4.具体代码:

private class UploadTask extends AsyncTask<String, Integer, String> {
    private Activity mContext;
    public UploadTask(Activity context) {
        this.mContext = context;
    }
    @Override
    protected String doInBackground(String... urls) {
        for (String url : urls) {
            uploadFile(url);
        }
        return null;
    }
    protected void onPostExecute(String result) {
        
    }
    protected void onProgressUpdate(Integer... progress) {
        
    }

    // upload photos
    public void uploadFile(String uploadFile) {
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(UPLOAD_SERVER);
            MultipartEntity mpEntity = new MultipartEntity();
            File file = new File(uploadFile);
            ContentBody cbFile = new FileBody(file);
            mpEntity.addPart("imgFile", cbFile);
            mpEntity.addPart("user_id", new StringBody("123"));
            mpEntity.addPart("pic_note", new StringBody("test", Charset.forName("utf-8")));
            mpEntity.addPart("pic_address", new StringBody("test", Charset.forName("utf-8")));
            httppost.setEntity(mpEntity);
            HttpResponse response = httpclient.execute(httppost);
            int statusCode=response.getStatusLine().getStatusCode();
            if(200 == statusCode){
                showToast(getString(R.string.upload_ok));
                String result = EntityUtils.toString(response.getEntity());
            }
            httpclient.getConnectionManager().shutdown();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
UploadTask ut = new UploadTask(SpotsActivity.this);
ut.execute(urls); //urls为本地图片路径数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LakeSideHu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值