【问题标题】:Save base64 file received from HttpPostedFileBase保存从 HttpPostedFileBase 收到的 base64 文件
【发布时间】:2017-06-23 22:18:27
【问题描述】:

我正在使用 jquery filedrop,但在 Internet Explorer (10+) 上使用 readAsBinaryString 时遇到错误。它适用于 Chrome 和 Firefox。

然后我将该方法更改为readAsDataURL,它在每个浏览器中都“有效”。

问题是最后一个方法从HttpPostedFileBase返回一个base64文件,我不知道如何按原样保存文件。

现在这是我的代码:

byte[] binaryData;
binaryData = new Byte[file.InputStream.Length];
long bytesRead = file.InputStream.Read(binaryData, 0, (int)file.InputStream.Length);
file.InputStream.Close();
string base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

byte[] bytes = System.Convert.FromBase64String(base64String);

string filePath = Path.Combine(ed_fisico_provisorio.vr_parametro, no_arquivo_provisorio);

System.IO.FileStream fs = System.IO.File.Create(filePath);
fs.Write(bytes, 0, bytes.Length);
fs.Close();

但是这样保存,文件的内容就变成这样了

数据:应用程序/msword;base64,0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAAAPgADAP7...

还有其他想法吗?

----- 更新 -----

为了澄清,一步一步发生了什么。顺便说一句,我正在使用 C# MVC。

第 1 步 - 使用插件 jquery.filedrop.js,我将文件放在其视图上。可以是任何文件扩展名。

STEP 2 - 调用插件,其中包含以下代码:

// Respond to an upload
        function upload() {

            stop_loop = false;

            if (!files) {
                opts.error(errors[0]);
                return false;
            }

            var filesDone = 0,
                filesRejected = 0;

            if (files_count > opts.maxfiles && opts.queuefiles === 0) {
                opts.error(errors[1]);
                return false;
            }

            // Define queues to manage upload process
            var workQueue = [];
            var processingQueue = [];
            var doneQueue = [];

            // Add everything to the workQueue
            for (var i = 0; i < files_count; i++) {
                workQueue.push(i);
            }

            // Helper function to enable pause of processing to wait
            // for in process queue to complete
            var pause = function (timeout) {
                setTimeout(process, timeout);
                return;
            }

            // Process an upload, recursive
            var process = function () {

                var fileIndex;

                if (stop_loop) return false;

                // Check to see if are in queue mode
                if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) {

                    return pause(opts.queuewait);

                } else {

                    // Take first thing off work queue
                    fileIndex = workQueue[0];
                    workQueue.splice(0, 1);

                    // Add to processing queue
                    processingQueue.push(fileIndex);

                }

                try {
                    if (beforeEach(files[fileIndex]) != false) {
                        if (fileIndex === files_count) return;
                        var reader = new FileReader(),
                            max_file_size = 1048576 * opts.maxfilesize;

                        reader.index = fileIndex;
                        if (files[fileIndex].size > max_file_size) {
                            opts.error(errors[2], files[fileIndex], fileIndex);
                            // Remove from queue
                            processingQueue.forEach(function (value, key) {
                                if (value === fileIndex) processingQueue.splice(key, 1);
                            });
                            filesRejected++;
                            return true;
                        }
                        reader.onloadend = send;





                        //reader.readAsArrayBuffer(files[fileIndex]);


                        reader.readAsDataURL(files[fileIndex]);



                        //reader.readAsBinaryString(files[fileIndex]);

                    } else {
                        filesRejected++;
                    }
                } catch (err) {
                    // Remove from queue
                    processingQueue.forEach(function (value, key) {
                        if (value === fileIndex) processingQueue.splice(key, 1);
                    });
                    opts.error(errors[0]);
                    return false;
                }

                // If we still have work to do,
                if (workQueue.length > 0) {
                    process();
                }

            };

            var send = function (e) {

                var fileIndex = ((typeof (e.srcElement) === "undefined") ? e.target : e.srcElement).index

                // Sometimes the index is not attached to the
                // event object. Find it by size. Hack for sure.
                if (e.target.index == undefined) {
                    e.target.index = getIndexBySize(e.total);
                }

                var xhr = new XMLHttpRequest(),
                    upload = xhr.upload,
                    file = files[e.target.index],
                    index = e.target.index,
                    start_time = new Date().getTime(),
                    boundary = '------multipartformboundary' + (new Date).getTime(),
                    builder;

                newName = rename(file.name);
                mime = file.type
                if (typeof newName === "string") {
                    builder = getBuilder(newName, e.target.result, mime, boundary);
                } else {
                    builder = getBuilder(file.name, e.target.result, mime, boundary);
                }

                upload.index = index;
                upload.file = file;
                upload.downloadStartTime = start_time;
                upload.currentStart = start_time;
                upload.currentProgress = 0;
                upload.startData = 0;
                upload.addEventListener("progress", progress, false);


                xhr.open("POST", opts.url, true);
                xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);

                // Add headers
                $.each(opts.headers, function (k, v) {
                    xhr.setRequestHeader(k, v);
                });

                xhr.sendAsBinary(builder);

                opts.uploadStarted(index, file, files_count);

                xhr.onload = function () {
                    if (xhr.responseText) {
                        var now = new Date().getTime(),
                            timeDiff = now - start_time,
                            result = opts.uploadFinished(index, file, jQuery.parseJSON(xhr.responseText), timeDiff, xhr);
                        filesDone++;

                        // Remove from processing queue
                        processingQueue.forEach(function (value, key) {
                            if (value === fileIndex) processingQueue.splice(key, 1);
                        });

                        // Add to donequeue
                        doneQueue.push(fileIndex);

                        if (filesDone == files_count - filesRejected) {
                            afterAll();
                        }
                        if (result === false) stop_loop = true;
                    }
                };

            }

            // Initiate the processing loop
            process();

        }

第 3 步 - 插件返回到我接收文件的控制器并尝试保存它:

[HttpPost]
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
            {                
                    byte[] binaryData;
                    binaryData = new Byte[file.InputStream.Length];
                    long bytesRead = file.InputStream.Read(binaryData, 0, (int)file.InputStream.Length);
                    file.InputStream.Close();
                    string base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

                    byte[] bytes = System.Convert.FromBase64String(base64String);

                    //Salva arquivo físico em pasta provisória
                    string filePath = Path.Combine(ed_fisico_provisorio.vr_parametro, file.FileName);

                    System.IO.FileStream fs = System.IO.File.Create(filePath);

                    fs.Write(bytes, 0, bytes.Length);
                    fs.Close();
    }

保存的文件内容如上。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# jquery base64 httppostedfilebase filedrop.js


    【解决方案1】:

    有点不清楚您使用什么技术来接收文件(WEBAPI、MVC、Something Awesome),但我过去曾在 WebAPI 2 端点中使用过这种技术,并使用流处理文件数据。

        public async Task<IHttpActionResult> Post()
        {
            var provider = new MultipartMemoryStreamProvider();
            var stream = await Request.Content.ReadAsMultipartAsync(provider).ConfigureAwait(false);
    
            // Returns the first file it finds
            var fileStream = stream.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.FileName != null);
    
            // return a result
        }
    

    使用fileStream 对象,您可以使用fileStream.ReadAsStreamAsync()fileStream.ReadAsStringAsync()(如果文件内容是文本)。

    【讨论】:

    • Aaron,谢谢你的回答,但我不太明白你做了什么。所以我编辑我的帖子以澄清。
    猜你喜欢
    • 2013-04-08
    • 1970-01-01
    • 2015-09-27
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2015-01-03
    • 2015-12-08
    相关资源
    最近更新 更多