2
我正在使用AngularJS構建我的應用程序。其中,我有一個表格,用戶可以填寫信息。這會創建一個使用WebAPI POST到數據庫的對象。如何使用WebAPI中附加的文件發佈對象?
這裏的角碼:
$scope.test_object =
{
'Title': $scope.test_object.title,
'Description': $scope.test_object.description,
};
// POST to the database
$http.post(some_url, JSON.stringify($scope.test_object)).then(function (response) {
// do something
}
);
而且這是我在Visual Studio類:
public class ClassName
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
這工作,因爲它應該沒有問題。我的問題是表單有附加文件的能力。我在Visual Studio中的控制器發送的文件,下面的代碼:
public class FileUploadController : ApiController
{
[Route("api/upload")]
public async Task<HttpResponseMessage> Post()
{
try
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
//Save To this server location
var uploadPath = HttpContext.Current.Server.MapPath("~/Data");
//Save file via CustomUploadMultipartFormProvider
var multipartFormDataStreamProvider = new CustomUploadMultipartFormProvider(uploadPath);
// Read the MIME multipart asynchronously
await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);
// Show all the key-value pairs.
foreach (var key in multipartFormDataStreamProvider.FormData.AllKeys)
{
foreach (var val in multipartFormDataStreamProvider.FormData.GetValues(key))
{
Console.WriteLine(string.Format("{0}: {1}", key, val));
}
}
//In Case you want to get the files name
//string localFileName = multipartFormDataStreamProvider
// .FileData.Select(multiPartData => multiPartData.LocalFileName).FirstOrDefault();
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception e)
{
return new HttpResponseMessage(HttpStatusCode.NotImplemented)
{
Content = new StringContent(e.Message)
};
}
}
}
我發現這個代碼在網上和它的作品發送文件。這會將任何文件發送到指定的文件夾(/ Data)。
現在我的問題是:如何創建對象和附件之間的關係?如何判斷哪些文件與每個對象關聯?我以某種方式發送對象ID和文件嗎?
感謝您的任何幫助。