如何将音频文件上传到Parse.com - Android

时间:2015-06-03 21:59:52

标签: android file audio parse-platform upload

我有一个文件路径,我想上传到Parse.com。

例如,其中一个文件路径是: “/storage/emulated/0/app100/2015-06-04_00:45:16_RecordSound.3gp”

现在,我想将其上传到Parse.com。任何解决方案怎么做?

我试过为此编写一个方法,但它不起作用:

private ParseObject uploadAudioToParse(File audioFile, ParseObject po, String columnName){

    if(audioFile != null){
        Log.d("EB", "audioFile is not NULL: " + audioFile.toString());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(audioFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int read;
        byte[] buff = new byte[1024];
        try {
            while ((read = in.read(buff)) > 0)
            {
                out.write(buff, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] audioBytes = out.toByteArray();
        // Create the ParseFile
        ParseFile file = new ParseFile(audioFile.getName() , audioBytes);
        // Upload the file into Parse Cloud
        file.saveInBackground();
        po.put(columnName, file);
    }
    return po;
}

谢谢!

1 个答案:

答案 0 :(得分:6)

尝试以下方法:

private ParseObject uploadAudioToParse(File audioFile, ParseObject po, String columnName){

if(audioFile != null){
    Log.d("EB", "audioFile is not NULL: " + audioFile.toString());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BufferedInputStream in = null;
    try {
        in = new BufferedInputStream(new FileInputStream(audioFile));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    int read;
    byte[] buff = new byte[1024];
    try {
        while ((read = in.read(buff)) > 0)
        {
            out.write(buff, 0, read);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    byte[] audioBytes = out.toByteArray();

    // Create the ParseFile
    ParseFile file = new ParseFile(audioFile.getName() , audioBytes);
    po.put(columnName, file);

    // Upload the file into Parse Cloud
    file.saveInBackground();
    po.saveInBackground();
}
return po;

}

首先将对象放入ParseObject,然后保存文件。另外,我还添加了保存ParseObject(po.saveInBackground())。由于你修改了po,你也必须保存它。也许你在方法之外做了这个,但是你链接的代码并没有显示出来。

此外,也许可以尝试在AsyncTask中执行此操作并调用save(),以确保每个步骤都有效(如果一个保存或出现问题,取消任务),或使用SaveCallback k提供如下:ParseObject.saveInBackground(SaveCallback回调);并且在完成方法中,一旦ParseFile成功保存,就将保存调用到PO对象。

注意:ParseFile大小限制为10mb,因此如果音频文件大于此值,则会出现问题。