通过okhttp3上传文件
选择图像,doc或pdf后,我想将它们通过okhttp3。如何进行此操作?
@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK && requestCode==0){
Log.d("uri data",""+data.getData());
selectedFileUri = data.getData();
fileToBeUploaded = new File(""+selectedFileUri);
fileName = fileToBeUploaded.getName();
Log.d("filename",""+fileName);
并在okhttp 3中
RequestBody formBody = new MultipartBody.Builder() .setType(MultipartBody.FORM)
.addFormDataPart("data[User][user_picture]", fileToBeUploaded.getName(),RequestBody.create(MediaType.parse("*/*"), fileToBeUploaded))
显示的错误是
java.io.FileNotFoundException: content:/com.android.providers.media.documents/document/image%3A40227: open failed: ENOENT (No such file or directory)
谢谢。
回答:
所以我自己回答这个问题。
因此,我首先将输出流打开到一个临时文件。
imageTempUploadfile=new File(Environment.getExternalStorageDirectory()+"/inpaint/");if(!imageTempUploadfile.exists())
imageTempUploadfile.mkdirs();
imageTempUploadfile2 = new File(Environment.getExternalStorageDirectory() + "/inpaint/"+"file"+".docx");
OutputStream outputTempFileStream = new FileOutputStream(imageTempUploadfile2);
扩展名取决于mime类型。您可以通过以下方式找到mime类型
@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK && requestCode==0){
Log.d("uri data",""+data.getData());
String mimetype = context.getContentResolver().getType(data.getData());
selectedFileUri = data.getData();
现在从文件读取并将其内容写入临时文件
selectedFileInputStream = getContentResolver().openInputStream(selectedFileUri);
现在写入文件
try { try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = selectedFileInputStream.read(buffer)) != -1) {
outputTempFileStream.write(buffer, 0, read);
}
outputTempFileStream.flush();
} finally {
outputTempFileStream.close();
}
} catch (Exception e) {
e.printStackTrace(); // handle exception, define IOException and others
}
最后
MultipartUtility multipart = new MultipartUtility(urlLeaveFormApply, charset);multipart.addFilePart("data[User][user_picture]", imageTempUploadfile2);
成功之后的最后
imageTempUploadfile2.delete();
以上是 通过okhttp3上传文件 的全部内容, 来源链接: utcz.com/qa/428301.html