Question

I am trying to upload a file from the browser to an asp.NET service. I am using FileReader.readAsDataURL() and getting the file as data URL.

I am using this JavaScript code event.target.result.match(/,(.*)$/)[1] to get only my file in base64 format. This is what I am sending to the service.

Using the code below I am storing the file in isolated storage

IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(
     IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);

byte[] byteArray = Convert.FromBase64String(data);                    

IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myfile", 
      FileMode.Create, isoStore);

StreamWriter writer = new StreamWriter(stream);
writer.Write(byteArray);
writer.Close();

Unfortunately, the file that I am saving is corrupted. Am I doing something wrong? Is there a better method for doing this?

Edit: I am trying to achieve Gmail style file upload. I have tried with forms but it complicates things to much.

My ajax call looks like this:

var query = {
    "data": fileData,
    "fileName": fileName
};

$.ajax({
    type: "POST",
    url: "Page.aspx/UploadFile",
    data: JSON.stringify(query),
    contentType: "application/json; charset=utf-8",
    dataType: "JSON"});

Can it be something related to the UTF-8 encoding?

Was it helpful?

Solution

The problem was that I was writing the data incorrectly. You don't need a StreamWriter to write the data. IsolatedStorageFileStream is enough for that. So the code should be:

IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(
      IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);

byte[] byteArray = Convert.FromBase64String(data);                    

IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myfile", 
      FileMode.Create, isoStore);

stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top