File Upload ASP.NET MVC 3.0

后端 未结 21 1013
无人共我
无人共我 2020-11-22 01:09

(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)

I want to

21条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 01:39

    I have to upload file in 100 kb chunks of file and last of the upload file store in database using command. I hope, it will helpfull to you.

        public HttpResponseMessage Post(AttachmentUploadForm form)
        {
            var response = new WebApiResultResponse
            {
                IsSuccess = true,
                RedirectRequired = false
            };
    
            var tempFilesFolder = Sanelib.Common.SystemSettings.Globals.CreateOrGetCustomPath("Temp\\" + form.FileId);
    
            File.WriteAllText(tempFilesFolder + "\\" + form.ChunkNumber + ".temp", form.ChunkData);
    
            if (form.ChunkNumber < Math.Ceiling((double)form.Size / 102400)) return Content(response);
    
            var folderInfo = new DirectoryInfo(tempFilesFolder);
            var totalFiles = folderInfo.GetFiles().Length;
    
            var sb = new StringBuilder();
    
            for (var i = 1; i <= totalFiles; i++)
            {
                sb.Append(File.ReadAllText(tempFilesFolder + "\\" + i + ".temp"));
            }
    
            var base64 = sb.ToString();
            base64 = base64.Substring(base64.IndexOf(',') + 1);
            var fileBytes = Convert.FromBase64String(base64);
            var fileStream = new FileStream(tempFilesFolder + "\\" + form.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            fileStream.Seek(fileStream.Length, SeekOrigin.Begin);
            fileStream.Write(fileBytes, 0, fileBytes.Length);
            fileStream.Close();
    
            Directory.Delete(tempFilesFolder, true);
    
            var md5 = MD5.Create();
    
            var command = Mapper.Map(form);
            command.FileData = fileBytes;
            command.FileHashCode = BitConverter.ToString(md5.ComputeHash(fileBytes)).Replace("-", "");
    
            return ExecuteCommand(command);
        }
    

    Javascript (Knockout Js)

    define(['util', 'ajax'], function (util, ajax) {
    "use strict";
    
    var exports = {},
         ViewModel, Attachment, FileObject;
    
    //File Upload
    FileObject = function (file, parent) {
        var self = this;
        self.fileId = util.guid();
        self.name = ko.observable(file.name);
        self.type = ko.observable(file.type);
        self.size = ko.observable();
        self.fileData = null;
        self.fileSize = ko.observable(file.size / 1024 / 1024);
        self.chunks = 0;
        self.currentChunk = ko.observable();
    
        var reader = new FileReader();
    
        // Closure to capture the file information.
        reader.onload = (function (e) {
            self.fileData = e.target.result;
            self.size(self.fileData.length);
            self.chunks = Math.ceil(self.size() / 102400);
            self.sendChunk(1);
        });
    
        reader.readAsDataURL(file);
    
        self.percentComplete = ko.computed(function () {
            return self.currentChunk() * 100 / self.chunks;
        }, self);
    
        self.cancel = function (record) {
            parent.uploads.remove(record);
        };
    
        self.sendChunk = function (number) {
            var start = (number - 1) * 102400;
            var end = number * 102400;
            self.currentChunk(number);
            var form = {
                fileId: self.fileId,
                name: self.name(),
                fileType: self.type(),
                Size: self.size(),
                FileSize: self.fileSize(),
                chunkNumber: number,
                chunkData: self.fileData.slice(start, end),
                entityTypeValue: parent.entityTypeValue,
                ReferenceId: parent.detail.id,
                ReferenceName: parent.detail.name
            };
    
            ajax.post('Attachment', JSON.stringify(form)).done(function (response) {
                if (number < self.chunks)
                    self.sendChunk(number + 1);
                if (response.id != null) {
                    parent.attachments.push(new Attachment(response));
                    self.cancel(response);
                }
            });
        };
    };
    
    Attachment = function (data) {
        var self = this;
        self.id = ko.observable(data.id);
        self.name = ko.observable(data.name);
        self.fileType = ko.observable(data.fileType);
        self.fileSize = ko.observable(data.fileSize);
        self.fileData = ko.observable(data.fileData);
        self.typeName = ko.observable(data.typeName);
        self.description = ko.observable(data.description).revertable();
        self.tags = ko.observable(data.tags).revertable();
        self.operationTime = ko.observable(moment(data.createdOn).format('MM-DD-YYYY HH:mm:ss'));
    
        self.description.subscribe(function () {
            var form = {
                Id: self.id(),
                Description: self.description(),
                Tags: self.tags()
            };
    
            ajax.put('attachment', JSON.stringify(form)).done(function (response) {
                self.description.commit();
                return;
            }).fail(function () {
                self.description.revert();
            });
        });
    
        self.tags.subscribe(function () {
            var form = {
                Id: self.id(),
                Description: self.description(),
                Tags: self.tags()
            };
    
            ajax.put('attachment', JSON.stringify(form)).done(function (response) {
                self.tags.commit();
                return;
            }).fail(function () {
                self.tags.revert();
            });
        });
    };
    
    ViewModel = function (data) {
        var self = this;
    
        // for attachment
        self.attachments = ko.observableArray([]);
        $.each(data.attachments, function (row, val) {
            self.attachments.push(new Attachment(val));
        });
    
        self.deleteAttachmentRecord = function (record) {
            if (!confirm("Are you sure you want to delete this record?")) return;
            ajax.del('attachment', record.id(), { async: false }).done(function () {
                self.attachments.remove(record);
                return;
            });
        };
    
    
    exports.exec = function (model) {
        console.log(model);
        var viewModel = new ViewModel(model);
        ko.applyBindings(viewModel, document.getElementById('ShowAuditDiv'));
    };
    
    return exports;
    });
    

    HTML Code:

    Attachments
    @Html.AttachmentPicker("AC")
    Name Type Size (MB) Upload Time Tags Description Delete
    Files upload status
    Name Type Size (MB) Status
    No Records found.

提交回复
热议问题