LeanCloud 文件上传与下载-Android

来源:互联网 发布:linux c语言创建文件 编辑:程序博客网 时间:2024/06/07 05:48

文件上传

LeanCloud为用户文件上传开放了接口,用户可以通过调用接口将文件上传到云端,并且生成文件的url,用户也可以通过这个url下载已经上传的文件。
LeanCloud实现文件上传的步骤:

  1. 构建AVFile文件实体
  2. 调用文件上传接口

其中构建AVFile文件实体有3种方式:

  1. 从数据流构建文件
    AVFile支持图片、视频、音乐等常见的文件类型,在构建的时候传入对应的字节流即可。

    AVFile file = new AVFile("resume.txt","Working with LeanCloud is great!".getBytes());
  2. 从本地路径构建文件
    大多数客户端程序都会与本地文件系统交互,常见的就是读取文件,下面代码可以实现从本地文件路径构建AVFile,后面我们将会主要介绍这种方式。

    AVFile file = AVFile.withAbsoluteLocalPath("LeanCloud.png", Environment.getExternalStorageDirectory() + "/LeanCloud.png");
  3. 从网络路径构建文件
    从一个已知的url构建AVFile也是很常见的,例如我们获得了一个网页上的图片链接,可以通过以下代码构建AVFile。

    AVFile file = new AVFile("test.gif", "http://ww3.sinaimg.cn/bmiddle/596b0666gw1ed70eavm5tg20bq06m7wi.gif", new HashMap<String, Object>());

我们采取第二种方式构建AVFile以实现和android本地文件系统交互的目的。

为了完成文件的上传,我们需要完成以下步骤:

  1. 调用android本地文件管理器,选取想要上传的文件。
  2. 获得上传文件的绝对路径,构建AVFile。
  3. 调用LeanCloud文件上传接口,上传文件。

下面我们开始实现上述步骤:

  • 步骤1 调用android本地文件管理器
    android系统自带文件管理器,我们可以通过Intent实现,代码如下:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.setType("*/*");intent.addCategory(Intent.CATEGORY_OPENABLE);startActivityForResult(intent, 1);  //1是requestcode

    setType方法可以筛选文件的类型,*/*代表任意类型。使用startActivityForResult打开本地文件管理器,我们可以通过onActivityResult回调方法获取选择的文件Uri,从而实现文件路径及其信息的获取。

  • 步骤2 获取选择的文件路径及其附加信息(文件大小、文件名等)
    在onActivityResult方法中获取Uri,代码如下:

    if (resultCode == Activity.RESULT_OK) {    Uri fileUri = data.getData();    String[] filePathSplit = fileUri.getPath().split(":");    if (filePathSplit.length == 2) {        //高版本系统内置文件选择器,只能从uri中得到相对路径,形式为:primary:文件相对路径        String relativeFilePath = null;        relativeFilePath = filePathSplit[1];        mFilePath = Environment.getExternalStorageDirectory() + "/" + relativeFilePath;    } else {        //低版本系统文件选择器,可以直接从uri中得到绝对路径        mFilePath = fileUri.getPath();    }    String[] folders = mFilePath.split("/");    mFileName = folders[folders.length-1];    mFileNameTextView.setText(mFileName);    Log.d("saved", "选择了文件:" + mFilePath);} else {    Log.d("saved", "没有选择文件");}

    我们首先获取返回的Intent中附带的的文件uri,然后通过uri的getpath方法获取文件在内部存储器中的文件路径。请注意这里的内部存储器,请勿选择sd卡中的文件。getExternalStorageDirectory()方法可以获取内部存储器的路径。

  • 步骤3 构建AVFile,上传文件
    获取了文件在内部存储器中的路径后,我们就可以构建AVFile,代码如下:

    AVFile loadingFile = null;try {    loadingFile = AVFile.withFile(mFileName, file);} catch (FileNotFoundException e) {    e.printStackTrace();}

    调用saveInBackground方法,上传文件。代码如下:

    loadingFile.saveInBackground(new SaveCallback() {    @Override    public void done(AVException e) {        if (e == null) {            Log.d("saved", "文件上传成功!");        } else {            Log.d("saved", "文件上传失败! " + e.getMessage() + "|" + e.getCause());        }    }}, new ProgressCallback() {    @Override    public void done(final Integer integer) {        getActivity().runOnUiThread(new Runnable() {            @Override            public void run() {                mSendProgress.setText("正在上传..." + integer + "%");            }        });    }});

    通过SaveCallback接口查看文件上传情况,ProgressCallback接口查看文件上传进度。

文件下载

文件下载比文件上传更为简单,为了实现文件的上传,我们需要完成以下步骤:

  • 获取云端文件url
  • 根据url构建AVFile
  • 调用接口下载文件

下面我们开始实现以上步骤:
- 步骤1 获取待下载文件的的url
上传到云端的文件被存储在_file表中,每一条file记录都有一个url属性。所以我们只需要根据id获取file记录,即可拿到url。代码如下:

```AVQuery<AVObject> query = new AVQuery<>("_File");query.getInBackground("58b133fe5c497d006782102f", new GetCallback<AVObject>() {    @Override    public void done(AVObject avObject, AVException e) {        if (e == null) {            Log.d("saved", "文件找到了");        } else {            Log.d("saved", "出错了" + e.getMessage());        }    }});```
  • 步骤2构建AVFile
    上面我们已经提到了构建AVFile的三种方法,这里使用第三种:通过网络url构建AVFile,代码如下:

    AVFile file = new AVFile("test.txt", avObject.getString("url"), new HashMap<String, Object>());

    "test.txt"是文件名可以自由设置。

  • 步骤3调用接口,下载文件

    file.getDataInBackground(new GetDataCallback() {@Override    public void done(byte[] bytes, AVException e) {        if (e == null) {            Log.d("saved", "文件大小" + bytes.length);        } else {            Log.d("saved", "出错了" + e.getMessage());        }        File downloadedFile = new File(Environment.getExternalStorageDirectory() + "/test.png");        FileOutputStream fout = null;        try {            fout = new FileOutputStream(downloadedFile);            fout.write(bytes);            Log.d("saved", "文件写入成功.");            fout.close();        } catch (FileNotFoundException e1) {            e1.printStackTrace();            Log.d("saved", "文件找不到.." + e1.getMessage());        } catch (IOException e1) {            Log.d("saved", "文件读取异常.");        }    }}, new ProgressCallback() {    @Override    public void done(Integer integer) {        Log.d("saved", "文件下载进度" + integer);    }});

    getDataInBackground方法如果读取文件成功会获得字节流存入bytes字节数组中。我们可以通过FileOutputStream文件输入流,将字节数组写入本地文件。当然写入之前我们需要先新建一个本地文件:

    File downloadedFile = new File(Environment.getExternalStorageDirectory() + "/test.png");

    本地文件存入内部存储器。与上传文件相同,我们同样可以通过ProgressCallback接口,获取文件的下载进度。


至此LeanCloud 的文件上传与下载就介绍完毕,代码尚不完善,这里仅仅演示一下如何使用LeanCloud上传和下载文件。

1 0
原创粉丝点击