T. Ferreira T. Ferreira - 2 months ago 10
AngularJS Question

How to POST an object with a file attached in WebAPI?

I'm using AngularJS to build my application. In it, I have a form that the user can fill with information. That creates an object that POSTs to a database using WebAPI.

Here's the Angular code:

$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
}
);


And here's my class in Visual Studio:

public class ClassName
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}


This works as it should with no problems. My problem is that the form has the capability of attaching a file. I have a controller in Visual Studio to send the file, here's the code:

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)
};
}
}
}


I found this code online and it works for sending files. This sends any file to the specified folder (/Data).

Now my question is: how do I create a relationship between the object and the attachment? How can I tell which files are associated with each object? Do I send the object ID along with the file somehow?

Thanks for any help.

Answer

What you can do in these situations is save the address of where the file is kept in a property of the object. So for instances, you could add a property to your class like this:

public class ClassName
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string FilePath { get; set; }
}

And then when you write your file to a directory you copy the address of the file to the FilePath property.