无法从Dropbox的下载文件 [英] cannot download file from dropbox

查看:408
本文介绍了无法从Dropbox的下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上传和下载Dropbox的从一个文件中。当我上传的文件是正确上传的。当我下载一个文件并打开它,该文件是零字节。谁能告诉我,为什么发生这种情况? 下载code:

 尝试{

                文件localFile =新的文件(localFilePath);
                文件fil​​eSelected =新的文件(dropboxPath);

                如果(!localFile.exists()){
                    localFile.createNewFile();
                } 其他 {
                    //拷贝(fileSelected,localFile);
                    //mApi.copy("/Test/test.png,/sdcard/testfile.png);

                    的BufferedInputStream BR = NULL;
                    的BufferedOutputStream体重= NULL;
                    DropboxInputStream的fd;
                    尝试 {
                        FD = mApi.getFileStream(fileSelected.getPath(),NULL);
                        BR =新的BufferedInputStream(FD);
                        体重=新的BufferedOutputStream(新的FileOutputStream(localFile));

                        byte []的缓冲区=新的字节[4096];
                        INT读取;
                        而(真){
                            读= br.read(缓冲区);
                            如果(读< = 0){
                                打破;
                            }
                            bw.write(缓冲,0,读);
                        }

                    }赶上(DropboxException E){
                        e.printStackTrace();
                    }赶上(FileNotFoundException异常E){
                        // TODO自动生成的catch块
                        e.printStackTrace();
                    }赶上(IOException异常E){
                        e.printStackTrace();
                    } 最后 {
                        如果(BW!= NULL){
                            尝试 {
                                bw.close();
                                如果(BR!= NULL){
                                    br.close();
                                }
                            }赶上(IOException异常E){
                                e.printStackTrace();
                            }
                        }

                    }
                } / *
                其他 {
                    showToast(文件已存在);
                } * /
            }
            赶上(IOException异常E){
                showToast(异常);
                e.printStackTrace();
            }
赶上(例外五){
    showToast(异常);
    e.printStackTrace();
}
 

解决方案

  / *
 *版权所有(C)2010  -  11年度的Dropbox公司
 *
 *特此授权,免费的,任何人
 *获得该软件副本及相关文档
 *文件(软件),以处理本软件不
 *限制,包括但不限于使用权,
 *复制,修改,合并,发布,分发,再许可和/或出售
 *拷贝软件,并允许个人向谁
 *软件附有这样做,受到以下
 *条件:
 *
 *以上版权声明和本许可通告
 *包括在所有副本或实质性部分的软件。
 *
 *本软件按原样,没有任何形式的担保,
 * EX $ P $干燥综合征或暗示,包括但不限于的担保
 *适销性,适用于某种特定用途的
 *不侵权。在任何情况下,作者或版权所有
 *持有人承担任何索赔,损失或其他责任,
 *无论是因执行合同,侵权还是其他原因,
 * FROM,淘汰或与本软件或使用,或
 *在软件的其他交易。
 * /


包codelynks.easydropbox;

进口android.app.ProgressDialog;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.DialogInterface.OnClickListener;
进口android.graphics.drawable.Drawable;
进口android.os.AsyncTask;
进口android.widget.Toast;

进口com.dropbox.client2.DropboxAPI;
进口com.dropbox.client2.DropboxAPI.Entry;
进口com.dropbox.client2.ProgressListener;
进口com.dropbox.client2.exception.DropboxException;
进口com.dropbox.client2.exception.DropboxIOException;
进口com.dropbox.client2.exception.DropboxParseException;
进口com.dropbox.client2.exception.DropboxPartialFileException;
进口com.dropbox.client2.exception.DropboxServerException;
进口com.dropbox.client2.exception.DropboxUnlinkedException;

进口java.io.FileNotFoundException;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;

/ **
 *在这里我们得到的元数据目录和下载文件的
 *后台线程,试图表现出典型的异常处理和流量
 *控制一个应用程序,从下载Dropbox的文件。
 * /

公共类下载扩展的AsyncTask<虚空龙,布尔> {


    私人语境mContext;
    私人最终ProgressDialog mDialog;
    私人DropboxAPI<> MAPI;
    私人字符串的mpath;

    私人绘制对象mDrawable;

    私人的FileOutputStream mFos;

    私人布尔mCanceled;
    私人龙mFileLen;
    私人字符串mErrorMsg;
    私人字符串mDownloadpath;

    //注意,由于我们使用一个单一的文件名这里为了简单起见,就
    //将无法使用此code两个同时下载。
    私人最终静态字符串映像文件=dbroulette.png;

    公共下载(上下文的背景下,DropboxAPI<> API,
                    字符串dropboxPath,字符串downloadpath){
        //我们设置的背景下这种方式使我们不小心泄露活动
        mContext = context.getApplicationContext();

        MAPI = API;
        的mpath = dropboxPath;
        mDownloadpath = downloadpath;
        mDialog =新ProgressDialog(上下文);
        mDialog.setMax(100);
        mDialog.setMessage(下载文件);
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setProgress(0);

        mDialog.setButton(ProgressDialog.BUTTON_POSITIVE,取消,新OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){
                mCanceled = TRUE;
                mErrorMsg =取消;

                //这将通过关闭取消getThumbnail操作
                //其流
                如果(mFos!= NULL){
                    尝试 {
                        mFos.close();
                    }赶上(IOException异常E){
                    }
                }
            }
        });

        mDialog.show();
        mDialog.setCanceledOnTouchOutside(假);
    }

    @覆盖
    保护布尔doInBackground(空... PARAMS){
        尝试 {
            如果(mCanceled){
                返回false;
            }

            //获取元数据目录
            项的dirent = mApi.metadata(的mpath,1000,空,真,空);

            如果(dirent.isDir){
                //这不是一个目录,或者有没有在这
                mErrorMsg =目录不能下载;
                返回false;
            }


            如果(mCanceled){
                返回false;
            }

            尝试 {
                mFos =新的FileOutputStream(mDownloadpath);
            }赶上(FileNotFoundException异常E){
                mErrorMsg =无法创建本地文件存储图像;
                返回false;
            }
            mApi.getFile(的mpath,空,mFos,新ProgressListener(){
                @覆盖
                众长progressInterval(){
                    返回500;
                }

                @覆盖
                公共无效onProgress(长为arg0,长ARG1){
                    mFileLen = ARG1; //文件总长度
                    publishProgress(将arg0); //下载的文件长度
                }
            });


            如果(mCanceled){
                返回false;
            }


            //我们必须有一个合法的图片
            返回true;

        }赶上(DropboxUnlinkedException E){
            //该AuthSession未正确验证或用户未链接。
        }赶上(DropboxPartialFileException E){
            //我们取消了操作
            mErrorMsg =下载已取消;
        }赶上(DropboxServerException E){
            //服务器端异常。这些都是会发生什么的例子,
            //但是我们不与他们在这里做什么特别的。
            如果(e.error == DropboxServerException._304_NOT_MODIFIED){
                //不会发生,因为我们不通过修订中的元数据
            }否则,如果(e.error == DropboxServerException._401_UNAUTHORIZED){
                //未经授权的,所以我们应该取消它们的链接。您可能要
                //自动注销用户在这种情况下。
            }否则,如果(e.error == DropboxServerException._403_FORBIDDEN){
                //不允许访问此
            }否则,如果(e.error == DropboxServerException._404_NOT_FOUND){
                //路径未找到(或如果它是缩略图,不能
                //缩略图)
            }否则,如果(e.error == DropboxServerException._406_NOT_ACCEPTABLE){
                //太多的条目返回
            }否则,如果(e.error == DropboxServerException._415_UNSUPPORTED_MEDIA){
                //不能缩略
            }否则,如果(e.error == DropboxServerException._507_INSUFFICIENT_STORAG​​E){
                // 用户超出配额
            } 其他 {
                //别的东西
            }
            //这得到了Dropbox的错误,翻译成用户的语言
            mErrorMsg = e.body.userError;
            如果(mErrorMsg == NULL){
                mErrorMsg = e.body.error;
            }
        }赶上(DropboxIOException E){
            //发生的时间,可能要自动重试。
            mErrorMsg =网络错误重试。;
        }赶上(DropboxParseException E){
            //可能是由于Dropbox的服务器重新启动后,应重试
            mErrorMsg =。Dropbox的错误重试。;
        }赶上(DropboxException E){
            // 未知错误
            mErrorMsg =未知错误重试。;
        }
        返回false;
    }

    @覆盖
    保护无效onProgressUpdate(长...进度){
        INT百分比=(INT)(100.0 *(双)进展[0] / mFileLen + 0.5);
        mDialog.setProgress(百分比);
    }

    @覆盖
    保护无效onPostExecute(布尔结果){
        mDialog.dismiss();
        如果(结果){
            showToast(下载完成);
            //现在我们把它设置图像
            //mView.setImageDrawable(mDrawable);
        } 其他 {
            //无法下载它,所以显示错误
            showToast(mErrorMsg);
        }
    }

    私人无效showToast(弦乐味精){
        吐司错误= Toast.makeText(mContext,味精,Toast.LENGTH_LONG);
        error.show();
    }


}
 

  

通话一样跟着后台线程

 下载=新的下载(背景下,马皮,drop_box_file_path,sdcard_path_to_store);
        download.execute();
 

  

其中,MAPI是DropboxAPI参考

I am uploading and downloading a file from dropbox. when I upload a file it uploads it correctly. when I download a file and open it, the file is zero bytes. can someone tell me why this is happening? download code:

            try{

                File localFile = new File(localFilePath);
                File fileSelected = new File(dropboxPath);

                if (!localFile.exists()) {
                    localFile.createNewFile();
                } else {
                    //copy(fileSelected, localFile);
                    //mApi.copy("/Test/test.png", "/sdcard/testfile.png");

                    BufferedInputStream br = null;
                    BufferedOutputStream bw = null;
                    DropboxInputStream fd;
                    try {
                        fd = mApi.getFileStream(fileSelected.getPath(), null);
                        br = new BufferedInputStream(fd);
                        bw = new BufferedOutputStream(new FileOutputStream(localFile));

                        byte[] buffer = new byte[4096];
                        int read;
                        while (true) {
                            read = br.read(buffer);
                            if (read <= 0) {
                                break;
                            }
                            bw.write(buffer, 0, read);
                        }

                    } catch (DropboxException e) {
                        e.printStackTrace();
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (bw != null) {
                            try {
                                bw.close();
                                if (br != null) {
                                    br.close();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }/*
                else {
                    showToast("File already exists");
                }*/
            } 
            catch (IOException e) {
                showToast("Exception");
                e.printStackTrace();
            }
catch (Exception e) {
    showToast("Exception");
    e.printStackTrace();
}

解决方案

/*
 * Copyright (c) 2010-11 Dropbox, Inc.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */


package codelynks.easydropbox;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.widget.Toast;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxIOException;
import com.dropbox.client2.exception.DropboxParseException;
import com.dropbox.client2.exception.DropboxPartialFileException;
import com.dropbox.client2.exception.DropboxServerException;
import com.dropbox.client2.exception.DropboxUnlinkedException;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Here we show getting metadata for a directory and downloading a file in a
 * background thread, trying to show typical exception handling and flow of
 * control for an app that downloads a file from Dropbox.
 */

public class Download extends AsyncTask<Void, Long, Boolean> {


    private Context mContext;
    private final ProgressDialog mDialog;
    private DropboxAPI<?> mApi;
    private String mPath;

    private Drawable mDrawable;

    private FileOutputStream mFos;

    private boolean mCanceled;
    private Long mFileLen;
    private String mErrorMsg;
    private String mDownloadpath;

    // Note that, since we use a single file name here for simplicity, you
    // won't be able to use this code for two simultaneous downloads.
    private final static String IMAGE_FILE_NAME = "dbroulette.png";

    public Download(Context context, DropboxAPI<?> api,
                    String dropboxPath, String downloadpath) {
        // We set the context this way so we don't accidentally leak activities
        mContext = context.getApplicationContext();

        mApi = api;
        mPath = dropboxPath;
        mDownloadpath = downloadpath;
        mDialog = new ProgressDialog(context);
        mDialog.setMax(100);
        mDialog.setMessage("Downloading File");
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setProgress(0);

        mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                mCanceled = true;
                mErrorMsg = "Canceled";

                // This will cancel the getThumbnail operation by closing
                // its stream
                if (mFos != null) {
                    try {
                        mFos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });

        mDialog.show();
        mDialog.setCanceledOnTouchOutside(false);
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            if (mCanceled) {
                return false;
            }

            // Get the metadata for a directory
            Entry dirent = mApi.metadata(mPath, 1000, null, true, null);

            if (dirent.isDir) {
                // It's not a directory, or there's nothing in it
                mErrorMsg = "Directory Can't be download";
                return false;
            }


            if (mCanceled) {
                return false;
            }

            try {
                mFos = new FileOutputStream(mDownloadpath);
            } catch (FileNotFoundException e) {
                mErrorMsg = "Couldn't create a local file to store the image";
                return false;
            }
            mApi.getFile(mPath, null, mFos, new ProgressListener() {
                @Override
                public long progressInterval() {
                    return 500;
                }

                @Override
                public void onProgress(long arg0, long arg1) {
                    mFileLen = arg1;//Total File Length
                    publishProgress(arg0);//Downloaded File Length
                }
            });


            if (mCanceled) {
                return false;
            }


            // We must have a legitimate picture
            return true;

        } catch (DropboxUnlinkedException e) {
            // The AuthSession wasn't properly authenticated or user unlinked.
        } catch (DropboxPartialFileException e) {
            // We canceled the operation
            mErrorMsg = "Download canceled";
        } catch (DropboxServerException e) {
            // Server-side exception.  These are examples of what could happen,
            // but we don't do anything special with them here.
            if (e.error == DropboxServerException._304_NOT_MODIFIED) {
                // won't happen since we don't pass in revision with metadata
            } else if (e.error == DropboxServerException._401_UNAUTHORIZED) {
                // Unauthorized, so we should unlink them.  You may want to
                // automatically log the user out in this case.
            } else if (e.error == DropboxServerException._403_FORBIDDEN) {
                // Not allowed to access this
            } else if (e.error == DropboxServerException._404_NOT_FOUND) {
                // path not found (or if it was the thumbnail, can't be
                // thumbnailed)
            } else if (e.error == DropboxServerException._406_NOT_ACCEPTABLE) {
                // too many entries to return
            } else if (e.error == DropboxServerException._415_UNSUPPORTED_MEDIA) {
                // can't be thumbnailed
            } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
                // user is over quota
            } else {
                // Something else
            }
            // This gets the Dropbox error, translated into the user's language
            mErrorMsg = e.body.userError;
            if (mErrorMsg == null) {
                mErrorMsg = e.body.error;
            }
        } catch (DropboxIOException e) {
            // Happens all the time, probably want to retry automatically.
            mErrorMsg = "Network error.  Try again.";
        } catch (DropboxParseException e) {
            // Probably due to Dropbox server restarting, should retry
            mErrorMsg = "Dropbox error.  Try again.";
        } catch (DropboxException e) {
            // Unknown error
            mErrorMsg = "Unknown error.  Try again.";
        }
        return false;
    }

    @Override
    protected void onProgressUpdate(Long... progress) {
        int percent = (int) (100.0 * (double) progress[0] / mFileLen + 0.5);
        mDialog.setProgress(percent);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        mDialog.dismiss();
        if (result) {
            showToast("Downloading Finished");
            // Set the image now that we have it
            //mView.setImageDrawable(mDrawable);
        } else {
            // Couldn't download it, so show an error
            showToast(mErrorMsg);
        }
    }

    private void showToast(String msg) {
        Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
        error.show();
    }


}

Call the background thread like followed

Download download = new Download(context, mApi, drop_box_file_path, sdcard_path_to_store);
        download.execute();

Where, mApi is the reference of DropboxAPI

这篇关于无法从Dropbox的下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆