(Android) Upload Files

public static String uploadFile(String filePath) {


DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(Constant.UPLOAD_IMAGE_URL);
File file = new File(filePath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("img", cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
String result = "";
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
if (!TextUtils.isEmpty(result)) {
return result;
}
resEntity.consumeContent();
return "";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return "";


}


private static final int TIME_OUT = 10 * 1000;
private static final String CHARSET = "utf-8";


public static String uploadImage(String imagePath) throws Exception {
String responseUrl = "";


String CONTENT_TYPE = "multipart/form-data";
String BOUNDARY = UUID.randomUUID().toString();


URL url = new URL(Constant.UPLOAD_IMAGE_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", CHARSET);
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
FileInputStream fs = new FileInputStream(imagePath);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fs.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
fs.close();
dos.flush();
int res = conn.getResponseCode();
if (res == 200) {
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
String result = "";
result = sb1.toString();
} else {
}
return responseUrl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值