I am trying to upload a file and send it to the service layer to save, however I keep finding examples on how the controller gets the HTTPPostedFileBase and saves it directly in the controller. My service layer has no depencies on the web dll hence do I need to read my object into a memory stream/ byte? Any pointers on how I should go about this is greatly appreciated...
Note: Files can by pdf, word so I may need to check content type also (maybe within the domain-service layer...
Code:
public ActionResult UploadFile(string filename, HttpPostedFileBase thefile)
{
//what do I do here...?
}
EDIT:
public interface ISomethingService
{
void AddFileToDisk(string loggedonuserid, int fileid, UploadedFile newupload);
}
public class UploadedFile
{
public string Filename { get; set; }
public Stream TheFile { get; set; }
public string ContentType { get; set; }
}
public class SomethingService : ISomethingService
{
public AddFileToDisk(string loggedonuserid, int fileid, UploadedFile newupload)
{
var path = @"c:\somewhere";
//if image
Image _image = Image.FromStream(file);
_image.Save(path);
//not sure how to save files as this is something I am trying to find out...
}
}
You could use the InputStream property of the posted file to read the contents as a byte array and send it to your service layer along with other information such as ContentType and FileName that your service layer might need:
public ActionResult UploadFile(string filename, HttpPostedFileBase thefile)
{
if (thefile != null && thefile.ContentLength > 0)
{
byte[] buffer = new byte[thefile.ContentLength];
thefile.InputStream.Read(buffer, 0, buffer.Length);
_service.SomeMethod(buffer, thefile.ContentType, thefile.FileName);
}
...
}
Can't you create a method on the service layer accepting a Stream
as a parameter and pass the theFile.InputStream
to it ? Stream does not requires any web related dependency, and you avoid to duplicate memory by copying the data in some other data structures to consume it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With