通过okhttp3上传文件

问题描述

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

因此,我首先将输出流打开到一个临时文件

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();

解决方法

选择图像,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)

谢谢。

猜你在找的技术问答相关文章

如何检查配对的蓝牙设备是打印机还是扫描仪(Android)
是否允许实体正文进行HTTP DELETE请求?
如何将ZipInputStream转换为InputStream?
java.util.logging Java 8中的变量
PowerMockito.doReturn返回null
Java中的RESTful调用
Swing / Java:如何正确使用getText和setText字符串
特殊字符和重音字符
Android Studio中的ndk.dir错误
错误“找不到主类”