Parse: Uploading files to the cloud (.NET SDK)

· Tech · , , , ,

Parse API/SDK is very well documented but in some cases it’s good to see some examples from the community itself. In this post I’ll describe how easy it is to upload files with Parse using the .NET SDK.

This code is divided in three methods:

 

readFileToMemory

public static byte[] readFileToMemory(string _filePath)
{
	byte[] buffer;
	var filePath = _filePath;
	FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
	Console.WriteLine("READING FILE...");
	try
	{
		int length = (int)fileStream.Length; // get file length
		buffer = new byte[length]; // create buffer
		int count; // actual number of bytes read
		int sum = 0; // total number of bytes read
		// read until Read method returns 0 (end of the stream has been reached)
		while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
			sum += count; // sum is a buffer offset for next reading
	}
	finally
	{
		fileStream.Close();
	}

	return buffer;
}

 

uploadFileToParse

public static async Task uploadFileToParse(byte[] buffer, string fileName)
{
	//Upload file
	byte[] data = buffer;
	ParseFile file = new ParseFile(fileName, data);
	Console.WriteLine("UPLOADING FILE...");
	await file.SaveAsync();
	
	//Link file with object
	var jobApplication = new ParseObject("JobApplication");
	jobApplication["applicantName"] = "Joe Smith";
	jobApplication["applicantResumeFile"] = file;
	Console.WriteLine("SAVING OBJECT...");
	await jobApplication.SaveAsync();
	Console.WriteLine("FINISHED - press enter to exit");
}

 

Main

public static void Main(string[] args)
{
	ParseClient.Initialize("Your App Id", "Your .NET Key");
	string filePath = @"Filesimage.jpg";
	string fileName = Path.GetFileName(filePath);
	byte[] buffer;
	
        buffer = readFileToMemory(filePath);
	uploadFileToParse(buffer, fileName);
	Console.Read();
}

 

GitHub: get repo here

Written by almirmesic · · Tech · , , , ,
NextGoogle API + AngularJS: The first step - Authenticate and display data!