Save form-data in webapi C#

Asked

Viewed 550 times

1

I have the following code in Angular 2 for a form-data post method:

    upload(event) {
      let files: FileList = event.target.files;
      let formData = new FormData();
      for (let i = 0, f; f = files[i]; i++) {
        formData.append('attachment', files[i], f.name);
      }
     //call the angular http method
     this.http.
       .post(URL, formData)
       .map((res:Response) =>
          res.json()).subscribe(
             (success) => {
             alert(success._body);
          },
       (error) => alert(error))
      }
   }

It works perfectly by sending everything I’d like, my problem is now in creating the C#API, what kind will I get on the Formdata-compatible back? How do I manipulate it? Is it possible to save it in the bank? If not, how to save it in a folder? I appreciate all the help!

1 answer

0


I used this in Webapi in C# and it worked very well. I got this information a while back from Stackoverflow himself here: https://stackoverflow.com/questions/27965568/webapi-file-uploading-without-writing-files-to-disk

public async Task<IHttpActionResult> UploadFile()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return StatusCode(HttpStatusCode.UnsupportedMediaType);
    }        

    var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();

    foreach (var stream in filesReadToProvider.Contents)
    {
        var fileBytes = await stream.ReadAsByteArrayAsync();
    }
}
  • Excellent! I was able to read the information now, I will already mark as correct your answer, but as doubt: when saving as byte array in the bank, as in the future you search and convert it?

  • It all depends on how you are recording all the content. Because to "facilitate" I write the name of the file and type, then I return an object with the data to assemble.

  • If it’s not too much to ask, do you have any example of mounting this object? Because I’m afraid to record how bite[] and in return hit me to reconvert.

  • I no longer have the code in hand, but I would record Mimetype and do something like that to recover. var pdf = "data:" + Mimetype + "; Base64, " + byteArray; window.open(pdf); If an image is a tag, just do this: <img ng-src="data:image/JPEG;Base64,{imageAMostrar}}">

  • Cool! I think the idea is good right there, writing the name too. Thanks for all your help Marcio! Saved me a few hours.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.