我需要使用本机代码上传文件,没有库,因为我想学习更多。 我使用以下意图选择任何文件:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, FILE_REQUEST_CODE);
我使用以下代码获取路径和扩展名onActivityResult:
Uri uri = data.getData();
assert uri != null;
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
String displayName = null;
if (uriString.startsWith("content://"))
{ try (Cursor cursor = getContentResolver().query(uri, null, null, null, null))
{ if (cursor != null && cursor.moveToFirst()) { displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); }
}
}
else if (uriString.startsWith("file://"))
{
displayName = myFile.getName();
}
Log.i("response", "path:\t" + path + " display name:\t" + displayName);
String[] content_type = displayName.split("\\.");
Log.i("response", "content type:\t" + content_type[1] + "path:\t");
这里content_type[1]
将为我提供文件类型,以便我检查是否选择了图像。
我使用以下代码将压缩图像文件:
Bitmap bitmap = BitmapFactory.decodeFile("");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos);
我需要帮助的部分。
我对如何对HTTPURLConnection
属性进行编码感到困惑...
我需要将reqestmethod
设置为POST
ReadTimeout ConnectTimeout
其他必要属性是什么,以及在上传文件时如何获得进度。 只是将文件写入输出流中的异步任务部分,内容类型(如果是pdf exel文件等)并从服务器读取响应。请详细解释