首页 > 解决方案 > 使用 Retrofit 将视频文件上传到 android 中的服务器时出现 java.io.FileNotFoundException

问题描述

我正在尝试在使用 Retrofit 上传到服务器之前压缩视频。我已经尝试了在 stackoverflow 上发布的所有可能的解决方案,但仍然遇到相同的异常。但是,当 API 被命中时,它会抛出异常,如下所述:

java.io.FileNotFoundException: /data/user/0/com.flexyn.debug/files/mydir (是一个目录)

以下是我用来将文件保存到内部存储的方法:

private File convertVideoPathToFile() {
        FileOutputStream outputStream = null;
        file = new File(getFilesDir(),"flexyn_video");
        if (!file.exists()) {
            file.mkdirs();
        }else if(!file.isDirectory() && file.canWrite()){
            file.delete();
            file.mkdirs();
        }

        try {
            outputStream = openFileOutput(file.getName(), Context.MODE_PRIVATE);
            outputStream.write(videoPath.getBytes());
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

下面是调用API上传视频到服务器的方法:

@覆盖

 public void saveVideoPost(File file) {
        if (mView == null) {
            return;
        }
        mView.showLoadingLayout();
        ApiInterface apiInterface= ApiClient.getClient().create(ApiInterface.class);
        final RequestBody requestBody = RequestBody.create(MediaType.parse("video/*"), file);
        RequestBody caption = RequestBody.create(MediaType.parse("text/plain"), mView.getCaption());
        RequestBody privacy = RequestBody.create(MediaType.parse("text/plain"), mView.getPrivacyStatus());
        MultipartBody.Part imageFileBody = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
        apiInterface.postActivity(tags_ids.toString(),FlexynApplication.getInstance().getUserToken(),imageFileBody, caption, privacy)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<DefaultResponse>() {
                    @Override
                    public void call(DefaultResponse responseBody)
                    {
                        if(responseBody.getError_code()==200 && responseBody.isSuccess()){
                            mView.hideLoadingLayout();
                            Log.d(TAG, "uploaded successfully " +responseBody.getMessage());
                            success(responseBody);
                        }else{
                            mView.hideLoadingLayout();
                            error(responseBody.getMessage());
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
    // throwing error here 
                        mView.hideLoadingLayout();
                        error(AppConstant.ERROR_MESSAGE1);
                    }
                });
    }

标签: androidvideoserverretrofit2

解决方案


推荐阅读