Kate
Kate

Reputation: 1576

Convert HttpUploadedFileWrapper to something not in System.Web

I've implemented a file upload in ASP.Net MVC. I've created a view model that received the uploaded file as an HttpPostedFileWrapper and within the controller action I can save the file to disk.

However, I want to perform the actual save in service method which is in a class library that doesn't implement System.Web. I can't therefore pass the HttpPostedFileWrapper object to the service method.

Does anyone know how to achieve this, either by receiving the file as a different object or converting it to something else prior to passing it. The only way I can think of is to read the content of the file into a MemoryStream, and pass this along with the other parameters such as filename individually, but just wondered if there was a better way?

Thanks

Upvotes: 0

Views: 162

Answers (1)

Rion Williams
Rion Williams

Reputation: 76577

The best approach would probably be retrieving the image data (as a byte[]) and the name of the image (as a string) and passing those along to your service, similar to the approach you mentioned :

public void UploadFile(HttpPostedFileWrapper file)
{
        // Ensure a file is present
        if(file != null)
        {
            // Store the file data 
            byte[] data = null;
            // Read the file data into an array
            using (var reader = new BinaryReader(file.InputStream))
            {
                data = reader.ReadBytes(file.ContentLength);
            }
            // Call your service here, passing along the data and file name
            UploadFileViaService(file.FileName, data);
        }
}

Since a byte[] and a string are very basic primatives, you should have no problem passing them to another service. A Stream is likely to work as well, but they can be prone to issues like being closed, whereas a byte[] will already have all of your content.

Upvotes: 1

Related Questions