我正在尝试上传文件并将其发送到服务层进行保存,但是我一直在寻找控制器如何获取HTTPPostedFileBase并将其直接保存在控制器中的示例.我的服务层在web dll上没有依赖关系,因此我需要将我的对象读入内存流/字节吗?关于我应该怎么做的任何指示非常感谢…
注意:文件可以通过pdf,word,所以我可能还需要检查内容类型(可能在域服务层…
码:
- public ActionResult UploadFile(string filename,HttpPostedFileBase thefile)
- {
- //what do I do here...?
- }
编辑:
- 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,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...
- }
- }
解决方法
您可以使用已发布文件的
InputStream属性将内容作为字节数组读取,并将其与服务层可能需要的其他信息(如
ContentType和
FileName)一起发送到服务层:
- public ActionResult UploadFile(string filename,HttpPostedFileBase thefile)
- {
- if (thefile != null && thefile.ContentLength > 0)
- {
- byte[] buffer = new byte[thefile.ContentLength];
- thefile.InputStream.Read(buffer,buffer.Length);
- _service.SomeMethod(buffer,thefile.ContentType,thefile.FileName);
- }
- ...
- }