E
E
eRKa2016-11-21 21:48:42
ASP.NET
eRKa, 2016-11-21 21:48:42

How to upload a file in ASP.NET WebApi without writing it to disk?

In all examples, uploading a file to the web api is done through

var provider = new MultipartFormDataStreamProvider(path);
var result = await Request.Content.ReadAsMultipartAsync(provider);

And at this moment ReadAsMultipartAsync(provider) the downloaded file is written to disk along the path path.
And in order to change the file (picture: reduce the quality and size), I need to open the file for reading again, then change it, then rewrite it. In general, a lot of unnecessary gestures with the file system.
I searched the Internet and did not see examples of how to load a file into memory , take it from the content, change it as I need and then write it to disk once.
Content has ReadAsStreamAsync and ReadAsByteArrayAsync, but what to do with them in this case is not clear. Based on them, making Image.FromStream will not work.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
eRKa, 2016-11-21
@kttotto

Here is the solution:

var provider = new MultipartMemoryStreamProvider();
var result = await content.ReadAsMultipartAsync(provider);

var stream = provider.Contents[0];  // если гарантированно один файл передавался, иначе - пройдитесь с помощью foreach
var fileName = stream.Headers.ContentDisposition.FileName.Trim('"');
var imgStream = await stream.ReadAsStreamAsync();
var img = GetImageResize(Image.FromStream(imgStream), width, height);

img.Save($"{basePath}\\{fileName}");

As you noticed, just instead of a stream of this kind MultipartFormDataStreamProvider, this MultipartMemoryStreamProvider is created.

P
Peter, 2016-11-21
@petermzg

For example:

Stream stream =  await content.ReadAsStreamAsync();
Image image = Image.FromStream(stream);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question