简体   繁体   English

使用C#将上传到服务器的文件作为二进制字符串从javascript保存到文件

[英]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: 我正在使用js File API并使用FileReader读取文件,如下所示:

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: 这是读取器加载处理程序,其中我获取文件内容,并使用jquery.ajax调用将其发送到服务器:

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: 并且UploadedFile是:

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. 而不是使用JSON和AJAX组合。 You can write HTTPHandler to upload file and can call it using Ajax same way you have done in your code. 您可以编写HTTPHandler来上传文件,也可以使用Ajax来调用它,就像在代码中一样。

It will allow you to upload any kind of file and with minimum code change Example 它可以让你上传任何一种用最少的代码更改文件和实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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