1.httpurlConnectin上传
public void uploadForm( File uploadFile) throws IOException {
StringBuilder sb = new StringBuilder();
String header="Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE2MDkxNzA4MTgsImV4cCI6MTYwOTI1NzIxOH0.xW2umoBQK7pNLqjafaDvmFXJF9tUS_swczXocGFJvh8";
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=file; filename=" + uploadFile.getName()
+ "\r\n");
sb.append("Content-Type: application/octet-stream" + "\r\n");
sb.append("\r\n");
byte[] headerInfo = sb.toString().getBytes("UTF-8");
byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = new URL(uploadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("authorization",header);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("Content-Length",
String.valueOf(headerInfo.length + uploadFile.length() + endInfo.length));
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
InputStream in = new FileInputStream(uploadFile);
int count = 0;
int available = in.available();
out.write(headerInfo);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
count += len;
int progress = count * 100 / available;
Log.d(TAG, "上传进度: " + progress + " %");
updateProgress(progress);
}
out.write(endInfo);
in.close();
out.close();
if (conn.getResponseCode() == 200) {
System.out.println("文件上传成功");
String s = stream2String(conn.getInputStream());
Log.d(TAG, "uploadForm: " + s);
}
}
private static final String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";
public String stream2String(InputStream is) {
int len;
byte[] bytes = new byte[1024];
StringBuffer sb = new StringBuffer();
try {
while ((len = is.read(bytes)) != -1) {
sb.append(new String(bytes, 0, len));
}
is.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private void updateProgress(final int progress) {
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
2.Uri 转换为 filepath
public static String getMediaUriFromPath(Context context, Uri uri) {
Cursor cursor = context.getContentResolver().query(uri,
null
, null
, null
, null,
null);
String imgPath = null;
while (cursor.moveToNext()) {
imgPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
}
return imgPath;
}