(Android) Upload Files

来源:互联网 发布:知乎 健康果甲醛检测 编辑:程序博客网 时间:2024/06/06 12:30
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