【问题标题】:Uploading local .csv to Firebase Storage将本地 .csv 上传到 Firebase 存储
【发布时间】:2016-05-30 08:12:34
【问题描述】:

我正在为 schoolproject 创建一个应用程序,该应用程序从 firebase 数据库读取数据,将其转换为 .csv 文件,然后我想将此文件上传到 firebase 存储,以便用户可以仅通过 downloadUrl 共享它。

以下是用于创建 csvfile 然后将其上传到 firebase 存储的类。 请参阅 csvUploader。

import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.CancellableTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageMetadata;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class CsvHandler {

private MainActivity mainActivity;

public CsvHandler(MainActivity mainActivity) {
    this.mainActivity = mainActivity;
}

/**
 * Method that writes a two-dimensional array with strings, to a .csv-file with a specified
 * date as the filename.
 *
 * @param dataArray array to write to a .csv
 * @param callDate  specified date that gets passed to the filename
 */
public void writeFileFromArray(String callDate, String[][] dataArray) {
    String filename = callDate + ".csv";
    //Creates the String which will make up the text for the .csv
    String csvText = "";
    //Adds all elements in Array to the string
    //TODO: Make sure this parses the text correctly to .csv-file format (dependent on Sara & Annies method)
    for (int i = 0; i < dataArray.length; i++) {
        for (int j = 0; j < dataArray[0].length; j++) {
            csvText = csvText + dataArray[i][j];
        }
    }

    //Creates a FileOutputStream for writing the file to internal storage
    FileOutputStream outputStream;
    try {
        //Opens a FileOutputStream to a file with the specified filename.
        //Creates file if it doesn't exist.
        outputStream = mainActivity.openFileOutput(filename, Context.MODE_PRIVATE);
        //Writes the string to the specified file
        outputStream.write(csvText.getBytes());
        //Closes the FileOutputStream to produce a file
        outputStream.close();
    } catch (FileNotFoundException e) {
        Toast.makeText(mainActivity, "Internal Error: No such file found", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(mainActivity, "Internal Error: IOException", Toast.LENGTH_SHORT).show();
    }
}

/**
 * TESTMETOD
 * TODO: Ta bort innan merge med master. Låt stå till develop
 */
public void readCsvFile(String callDate) {
    try {
        String Message;
        FileInputStream fileInputStream = mainActivity.openFileInput(callDate + ".csv");
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuffer stringBuffer = new StringBuffer();
        while ((Message = bufferedReader.readLine()) != null) {
            stringBuffer.append(Message + "\n");
        }
        Toast.makeText(mainActivity, stringBuffer.toString(), Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Method to extract a filePath for a specified date.
 *
 * @param callDate a String with the date to return a filepath for
 * @return the filepath for the specified date
 */
public String getFilePath(String callDate) {
    String filePath = mainActivity.getFilesDir().getAbsolutePath() + callDate + ".csv";
    Log.e("LOG", "Output from getFilePath " + filePath);
    return filePath;
}


public void csvUploader(String filePath, final String callDate) {
    StorageReference mStorageReference = FirebaseStorage.getInstance().getReference();
    Log.e("LOG", "Entering CSVUPLOADER");
    Uri file = Uri.fromFile(new File(filePath));
    Log.e("csvUploader Uri File:", filePath.toString());

    // Create the file metadata
    StorageMetadata metadata = new StorageMetadata.Builder().setContentType("text/csv").build();
    Log.e("LOG","Metadata: " + metadata.toString());

    // Upload file and metadata to the path 'reports/date.csv'
    CancellableTask uploadTask = mStorageReference.child("reports/" + file.getLastPathSegment()).putFile(file, metadata);


    uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
            //System.out.println("Upload is " + progress + "% done");
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
            Log.e("LOG", "Unsucessfull in CSVUPLOADER");
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // Handle successful uploads on complete
            //Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
            //mainActivity.setDownloadLink(downloadUrl);
            Log.e("LOG", "Successfull in CSVUPLOADER");
            mainActivity.getUrlAsync(callDate);
        }
    });
}

}

其中大部分是来自 firebase.google.com 的示例代码,但我无法正常工作。

日志: E/LOG:getFilePath 的输出:/data/user/0/com.example.eliasvensson.busify/files2016-05-18.csv E/LOG:输入 CSVUPLOADER E/LOG:元数据:com.google.firebase.storage.StorageMetadata@7fd93a9 E/LOG: CSVUPLOADER 中不成功

怎么了? 我收集到我在我的存储桶上“保留”了路径,然后将文件放在那个地方。对吗?

任何帮助将不胜感激。

【问题讨论】:

    标签: java android csv mobile firebase


    【解决方案1】:

    这一切实际上几乎奏效了。

    filePath 错误,输出 /data/user/0/com.example.eliasvensson.busify/files2016-05-18.csv 期待的时候 /data/user/0/com.example.eliasvensson.busify/files/2016-05-18.csv(注意文件和日期之间的斜线)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-09
      • 2018-10-13
      • 1970-01-01
      • 2023-03-09
      • 2018-07-06
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      相关资源
      最近更新 更多