通过okhttp3上传文件

时间:2017-02-09 15:19:12

标签: java android file-upload okhttp okhttp3

选择image,doc或pdf之后,我想通过okhttp3传递它们。我该怎么做呢?

@Override
public 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)

感谢。

1 个答案:

答案 0 :(得分:1)

所以我自己回答这个问题。

所以我首先打开一个临时文件的输出流。

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类型
@Override
public 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();