What is the best way to upload files with ASP.NET MVC 2?

后端 未结 2 866
醉话见心
醉话见心 2021-01-12 22:04

What is the best method for uploading files of variable size (either very large or very small to an ASP.NET MVC 2 application file system)?

This is what I understa

相关标签:
2条回答
  • 2021-01-12 22:46

    I use this javascript tool

    This is the controller (I double check cause IE has a strange behavior) :

    <HttpPost()> _
    Function UploadExcelPriceList(ByVal id As String) As System.String
    
        Dim bResult As Boolean = False
        Dim IsIE As Boolean = False
        Dim sFileName As String = ""
    
        If (Request.Files Is Nothing) OrElse (Request.Files.Count = 0) Then
            If String.IsNullOrEmpty(Request.Params("qqfile")) Then
                Return ("{success:false, error:'request file is empty'}")
            Else
                sFileName = Request.Params("qqfile").ToString
            End If
        Else
            sFileName = Request.Files(0).FileName
            IsIE = True
        End If
    
        If String.IsNullOrEmpty(sFileName) Then
            Return ("{success:false, error:'request file is empty'}")
        End If
    
        Dim DocumentName As String = Id & Path.GetExtension(sFileName)
    
        If IsIE Then
            Try
                Request.Files(0).SaveAs(Path.Combine(My.Settings.TempFolder, DocumentName))
            Catch ex As Exception
                Return ("{success:false, error:'" & ex.Message & "'}")
            End Try
        Else
            Try
                If (Request.InputStream IsNot Nothing) AndAlso (Request.InputStream.CanRead) AndAlso (Request.InputStream.Length > 0) Then
                    Using fileStream As FileStream = New FileStream(Path.Combine(My.Settings.TempFolder, DocumentName), FileMode.Create)
                        Dim FileBytes(Core.Convert.ToInt32(Request.InputStream.Length)) As Byte
                        Dim bytesRead As Int32 = 0
                        bytesRead = Request.InputStream.Read(FileBytes, 0, FileBytes.Length)
                        fileStream.Write(FileBytes, 0, bytesRead)
                        fileStream.Flush()
                        fileStream.Close()
                        bytesRead = Nothing
                    End Using
                End If
            Catch ex As Exception
                Return ("{success:false, error:'" & ex.Message & "'}")
            End Try
        End If
    
        Return ("{success:true, id: '" & Id & "'}")
    
    End Function
    

    I put this HTML in my View:

    <div id="PopupExcelUploader" title="Carica Listino Excel">
        <div id="uploaderFile"></div>
    </div>
    

    and this is the javascript:

    function CreateFileUploader() {
        var uploader = new qq.FileUploader({
            element: $('#uploaderFile')[0],
            template: '<div class="qq-uploader">' +
                                  '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
                                  '<div class="qq-upload-button ui-button ui-widget ui-corner-all ui-button-text-only ui-state-default">Seleziona il Listino Excel</div>' +
                                  '<ul class="qq-upload-list"></ul>' +
                                  '</div>',
            hoverClass: 'ui-state-hover',
            focusClass: 'ui-state-focus',
            action: UploaderAction,
            allowedExtensions: ['xls', 'xlsx'],
            params: { id: ModelId },
            onSubmit: function(file, ext) {
            },
            onComplete: function(id, fileName, responseJSON) {
                if ((responseJSON.success == null) || (responseJSON.success == 'false')) {
                    $.jGrowl("Error!", { theme: 'MessageError', life: 3000 });
                }
                else {
                    documentUploaded = true;
                    $.jGrowl("Document uploaded successfully!", { theme: 'MessageOk', life: 1800 });
                    window.setTimeout(function() {
                        $("#PopupExcelUploader").dialog('close');
                        $("#PriceListDynamicGrid").trigger("reloadGrid");
                    }, 3000);
                }
            }
        });
    }
    
    0 讨论(0)
  • 2021-01-12 23:04

    If I remember correctly from ASP.NET 2.0 large files are being flushed to disk, so even using HttpPostedFileBase there should not be any memory/performance problems. I am not sure asynccontrollers is an solutions here, asynccontrollers is for long running server processes. For an example off AsyncControllers see http://www.aaronstannard.com/post/2011/01/06/asynchonrous-controllers-ASPNET-mvc.aspx

    0 讨论(0)
提交回复
热议问题