[筆記][WebAPI][Upload] WebAPI 檔案上傳範例

檔案上傳,是Web開發很普遍的一個需求。WebAPI的部分,要怎麼處理這一塊呢?請繼續看下去...

緣起

檔案上傳,是Web開發很普遍的一個需求。小喵由於最近轉為使用「Angular 2 (Angular 4) 搭配 WebAPI」,剛好最近同事有這麼一個需求,小喵就來測試並筆記一下。本篇是 WebAPI 的部分。

Controller 的部分

小喵把上傳的檔案,暫時放在App_Data中,路徑的部分,請大家依據自己的情況進行調整。相關程式碼如下:

Imports System.Net
Imports System.Net.Http
Imports System.Web.Http

Namespace Controllers
    Public Class UploadController
        Inherits ApiController

        <HttpPost>
        Public Function PostFormData() As HttpResponseMessage

            Try
                Dim Req As HttpRequest = HttpContext.Current.Request
                Dim f As HttpPostedFile
                Dim FilePath As String
                If (Req.Files.Count > 0) Then
                    For Each FileName As String In Req.Files.Keys
                        f = Req.Files(FileName)
                        FilePath = HttpContext.Current.Server.MapPath("~/App_Data/" & f.FileName)
                        f.SaveAs(FilePath)
                    Next
                End If
                Return Request.CreateResponse(HttpStatusCode.OK)
            Catch ex As Exception
                Return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)
            End Try
        End Function
    End Class
End Namespace

 

測試的Html

為了簡單方便的測試,我們在相同專案(WebAPI專案)中心增一個html,來進行測試,相關程式碼如下:

<form name="form1" method="post" enctype="multipart/form-data" action="api/upload">
	<div>
		<label for="caption">Image Caption</label>
		<input name="caption" type="text" />
	</div>
	<div>
		<label for="image1">Image File</label>
		<input name="image1" type="file" />
	</div>
	<div>
		<input type="submit" value="Submit" />
	</div>
</form>

 

參考資料:

https://stackoverflow.com/questions/33387764/how-to-post-file-to-asp-net-web-api-2

 

 

 

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat