owin webapi 和 mvc webapi 文件上传controller

Owin:
<HttpPost> Function UploadFileOwin() As IHttpActionResult Owin方式文件上传 If Request.Content.IsMimeMultipartContent("form-data") Then Dim ParentPath As String = System.Environment.CurrentDirectory & "/UploadFiles/" If Not Directory.Exists(ParentPath) Then Directory.CreateDirectory(ParentPath) End If Dim Provider = Request.Content.ReadAsMultipartAsync.Result If Provider.Contents.Count > 0 Then For Each c In Provider.Contents If c.Headers.ContentDisposition.FileName <> "" Then Dim filePath As String = String.Concat(ParentPath, c.Headers.ContentDisposition.FileName.Replace("""", "")) Using fs As FileStream = New FileStream(filePath, FileMode.OpenOrCreate) Using ioStream = c.ReadAsStreamAsync.Result Dim buff As Byte() = New Byte(ioStream.Length) {} Dim co = ioStream.Read(buff, 0, ioStream.Length) Using memStream = New MemoryStream(buff) memStream.WriteTo(fs) Return Ok("上传成功") End Using End Using End Using End If Next End If End If Return Ok("上传失败") End Function

mvc:
  
    <HttpPost>
    Function UploadFileMVC() As String MVC方式上传文件
        Dim result = String.Empty
        Dim uploadPath As String = HttpContext.Current.Server.MapPath("~/upload/")
        Dim uploadPath As String = System.Web.Hosting.HostingEnvironment.MapPath("~/upload/")
        Dim request As HttpRequest = HttpContext.Current.Request
        Dim fileCollection As HttpFileCollection = request.Files
        If fileCollection.Count > 0 Then
            Dim httpPostedFile As HttpPostedFile = fileCollection(0)
            Dim fileExtension As String = Path.GetExtension(httpPostedFile.FileName)
            Dim fileName As String = Guid.NewGuid().ToString() + fileExtension
            Dim filePath As String = uploadPath + httpPostedFile.FileName
            If Not Directory.Exists(uploadPath) Then
                Directory.CreateDirectory(uploadPath)
            End If
            While File.Exists(filePath)
                fileName = Guid.NewGuid().ToString() + fileExtension
                filePath = uploadPath + fileName
            End While
            httpPostedFile.SaveAs(filePath)
            Return "上传成功"
        End If
        Return "文件上传失败"
    End Function

 

 

 

owin webapi 和 mvc webapi 文件上传controller

上一篇:C#自定义控件


下一篇:Django之DRF-- API限速