AngularJS .Net WebAPI Upload image and save to dat

2020-07-20 03:11发布

问题:

I'm trying to upload an Image(can be bind to a model with a data type byte[]) from UI and save it in the database. I'm using AngularJS connecting it to .NET WebAPI and saving it to MSSSQL Server I cant find a good example using these technologies.

Question: What approach is better to use? like ng-upload, FormData, ArrayBuffer, convert image to byte, etc. and how will you catch it from WebAPI?

Thanks!

回答1:

I'm working on this feature these days. I share my experience (obviously it can be improved). The key components I use are:

  • angular-file-upload
  • .NET ImageResizer: for resizing original image for thumbnails (excellent work by Nathanael Jones)

the stack is:

Angular.js Image Uploader

As I said, I use angular-file-uploader. There's no so much to add to the official documentation, but my uploader configuration is:

$scope.uploader = $fileUploader.create({
    scope: $scope,
    url: DisciturSettings.apiUrl + 'User/Image',
    queueLimit: 1,
    formData: [{ UserId: AuthService.user.userid }],
    headers: AuthService.getTokenHeader()
});

In order to send the user id to the http request and to grant the access to the authorized route

WebApi 2 Action

The service does the main work. Here is the code. As you can see, in this phase, I do two resizings of the image passed (one for the user profile picture and the other for user thumbnail picture). Besides this, I convert the byte[] in string and prepare the string for next retrievals. Doing this I prepend this part "data:image/gif;base64,", so, in the next entity readings (through EntityFramework) I don't have to manipulate the result anymore and I can put them directly in angular template:

<img ng-src="{{local.user.image}}" />

Obviously It can be made differently, but that's my case.

Database

At the moment I simply use nvarchar for storing images.

It's my first try so it can be improved for sure (if you have hints, don't hesitate).