簡體   English   中英

使用C#將上傳到服務器的文件作為二進制字符串從javascript保存到文件

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

我正在使用js File API並使用FileReader讀取文件,如下所示:

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

這是讀取器加載處理程序,其中我獲取文件內容,並使用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');
            }
        });
    }

在服務器端,我有:

[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;
        }

並且UploadedFile是:

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

我設法保存文件,但是內容有所不同。 我知道它與編碼有關,但是我在服務器上沒有得到相同的文件。 你能告訴我我在做什么錯嗎?

您可以從上傳的文件中讀取所有內容,然后保存所有內容。
例如 :-

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

其他解決方案可能是(我也在使用)。 而不是使用JSON和AJAX組合。 您可以編寫HTTPHandler來上傳文件,也可以使用Ajax來調用它,就像在代碼中一樣。

它可以讓你上傳任何一種用最少的代碼更改文件和實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM