Skip to content

Instantly share code, notes, and snippets.

@jebai0521
Created September 16, 2015 03:53
Show Gist options
  • Save jebai0521/0732e30698893ad071b3 to your computer and use it in GitHub Desktop.
Save jebai0521/0732e30698893ad071b3 to your computer and use it in GitHub Desktop.
MultipartEntity 上传文件
public static String uploadFileV2(Context context, String RequestURL) throws JSONException
{
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String CONTENT_TYPE = "multipart/form-data"; // 内容类型
try
{
URL url = new URL(RequestURL);
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);
List<Long> ids = new ArrayList<Long>();
ids.add(new Long(9812));
ids.add(new Long(9813));
List<String> images = new ArrayList<String>();
images.add("/mnt/sdcard/DCIM/243c07a9eea96259a997e98f7e8ce71e.jpg");
images.add("/mnt/sdcard/DCIM/1.jpg");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setBoundary(BOUNDARY);
if (images.size() > 0)
{
for (int i = 0; i < images.size(); i++) {
builder.addBinaryBody(ids.get(i).toString(), new File(images.get(i)), ContentType.APPLICATION_OCTET_STREAM, images.get(i));
}
builder.build().writeTo(conn.getOutputStream());
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
Log.e("uploadUntils", "upload request==>" + res);
if (res == 200)
{
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1)
{
sb1.append((char) ss);
}
String result = sb1.toString();
JSONObject jsonObject = new JSONObject(result);
JSONArray rowsArray = jsonObject.getJSONArray("rows");
processResponseData(rowsArray);
return SUCCESS;
}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return FAILURE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment