下载文件并保存到光盘不起作用

时间:2019-04-26 13:38:17

标签: java android download

我需要从服务器下载文件,所以我正在使用改造和这种方法将文件保存到磁盘。

这是我的代码

    @GET
    Call<ResponseBody> downloadFileWithDynamicUrlSync(@Url String fileUrl);

下载文件的方法

 private void dowloadFile(String url, FileListItem item) {

        Call<ResponseBody> callb = RestClient.getInstance().getService().downloadFileWithDynamicUrlSync(url);

        callb.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "server contacted and has file");
                    boolean writtenToDisk = writeResponseBodyToDisk(response.body(), item);
                    if(writtenToDisk){
                        MdocUtil.showToastShort(context, context.getString(R.string.file_dowloaded_succ));
                    }else{
                        MdocUtil.showToastShort(context, context.getString(R.string.error_download));
                    }
                    Log.d(TAG, "file download was a success? " + writtenToDisk);
                } else {
                    Log.d(TAG, "server contact failed");
                    APIError error = ErrorUtils.parseError(response);
                    MdocUtil.showToastShort(context, error.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e(TAG, "error");
            }
        });
    }

将文件写入光盘的方法

 private boolean writeResponseBodyToDisk(ResponseBody body, FileListItem item) {
        try {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + item.getName());

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(file);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;

                    Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
                }

                outputStream.flush();

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }

此代码在查找图像时可以完美地工作,但不适用于.pdf和.docx文件,在这种情况下,writeToDisk为true,但手机上没有文件。

更新: 问题是我没有在标头中设置访问令牌,服务器要求文件而不是图像访问标头。

1 个答案:

答案 0 :(得分:2)

您为什么不使用本地Android下载管理器呢? 您可以see here下载管理器实用程序,可以用作以下示例:

downloadManager = new DownloadManager(new DownloadManager.DownloadCompleteListener(){
    @Override
    public void getProgress(double progress, long downloadedBytes, long sizeInBytes){

    }

    @Override
    public void onDownloadComplete(Uri fileLocalUri, long downloadedFileId){

    }
});
downloadManager.download(Uri uri, String fileName, String description);