ASP.NET Web Api client to upload file. Pass object to post method

半城伤御伤魂 提交于 2020-01-25 10:38:28

问题


I am trying to upload file to DB server through Web API client

VB class as below

Public Class Uploads
Public Property FileName As String
Public Property uploadDateTime As DateTime
Public Property File As Byte()
End Class

Then ASP.NET user upload the file using ASP.NET web form. After receieving this file we need to upload it to server through httpClient

    If FileUpload1.HasFile Then

        Dim newFile As New Uploads()

        newFile.FileName=FileUpload1.FileName
        newFile.uploadDateTime=DateTime.Now

        newFile.File = New Byte(FileUpload1.PostedFile.ContentLength) {}
        FileUpload1.FileContent.Read(newFile.File, 0, FileUpload1.PostedFile.ContentLength)

'Following class makes a call to web api
    Dim client As New apiClient()
    client.Upload(newFile)
        End if

Client for Web API (This is where I am struck. How do we pass a class object to web api through http client).

 Public Function Upload(ByVal newFile As Uploads)As Boolean


        Dim client As New HttpClient()
        client.BaseAddress = New Uri("http://localhost:8080/api/Upload")
        Dim content = New MultipartFormDataContent()

        'What I should do here to make a call to web api (cross domain)

return true
End Function

And then request should come to web api controller which finally will save the file to database through Entity Framework

<HttpPost()> _
    Public Sub PostValue(<FromBody()> ByVal newFile As Uploads)
        Using db As New DataContext()
            db.Uploadss.Add(newFile)
            db.SaveChanges()
        End Using

    End Sub

Any Code snippets will be very helpfull

来源:https://stackoverflow.com/questions/30347569/asp-net-web-api-client-to-upload-file-pass-object-to-post-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!