简体   繁体   中英

Save file uploaded to server as binary string from javascript to file using c#

I'm using js File API and reading file with FileReader like this:

var reader = new FileReader();
reader.onload = handleReaderLoad;
reader.readAsBinaryString(file);

and this is reader load handler in which I get file content and send it to server using jquery.ajax call:

function handleReaderLoad(evt) {
        fileToSend.Content = evt.target.result;

        $.ajax({
            url: '@Url.Action("Upload")',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ file: fileToSend }),
            success: function (result) {
                alert('success');
            }
        });
    }

on server side I have:

[HttpPost]
        public string Upload(UploadedFile file)
        {
            // save file
            try
            {
                FileStream fs = new FileStream(@"c:\" + file.Name, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(Encoding.UTF8.GetBytes(file.Content));
            }
            catch (Exception) { }
            return null;
        }

and the UploadedFile is:

public class UploadedFile
    {
        public string Name { get; set; }
        public string Content { get; set; }
    }

I managed to save file, but content is different. I know that it has something to do with encoding but I just don't get same file on server. Can you please tell what am I doing wrong?

you can read all the content from the uploaded file and then save all the content.
for Example :-

 Stream fileStream = fileUpload.PostedFile.InputStream;
 StreamReader sr = new StreamReader(fileStream);
 string str=sr.ReadToEnd();
 StreamWriter sw = new StreamWriter(fs);// your FileStream :-
 sw.WriteLine(str);

The other solution could be (which i am also using). Rather than using JSON and AJAX combination. You can write HTTPHandler to upload file and can call it using Ajax same way you have done in your code.

It will allow you to upload any kind of file and with minimum code change Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM