我正在为schoolproject创建一个应用程序,该应用程序从firebase数据库读取数据,将其转换为.csv文件,然后我想将此文件上传到firebase存储,以便用户可以只使用downloadUrl共享它。 / p>
下面是创建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中不成功
什么错了? 我收集到,我“保留”我的存储桶上的路径,然后将文件放在那个地方。这是对的吗?
任何帮助都将不胜感激。
答案 0 :(得分:0)
这一切实际上几乎都有效。
filePath错误,输出/data/user/0/com.example.eliasvensson.busify/files2016-05-18.csv 什么时候期待 /data/user/0/com.example.eliasvensson.busify/files/2016-05-18.csv(注意文件和日期之间的斜杠)