上传文件并发送到服务层,即c#类库

上传文件并发送到服务层,即c#类库,c#,asp.net-mvc,C#,Asp.net Mvc,我试图上传一个文件并将其发送到服务层进行保存,但是我一直在寻找控制器如何获取HTTPPostedFileBase并将其直接保存在控制器中的示例。我的服务层不依赖于web dll,因此我是否需要将对象读入内存流/字节?任何关于我应该如何做的建议都非常感谢 注意:文件可以通过pdf,word,所以我可能还需要检查内容类型(可能在域服务层内 代码: 编辑: public interface ISomethingService { void AddFileToDisk(string logg

我试图上传一个文件并将其发送到服务层进行保存,但是我一直在寻找控制器如何获取HTTPPostedFileBase并将其直接保存在控制器中的示例。我的服务层不依赖于web dll,因此我是否需要将对象读入内存流/字节?任何关于我应该如何做的建议都非常感谢

注意:文件可以通过pdf,word,所以我可能还需要检查内容类型(可能在域服务层内

代码:

编辑:

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...
  } 
}
您可以使用发布文件的属性以字节数组的形式读取内容,并将其与服务层可能需要的其他信息(如和)一起发送到服务层:

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);
    }
    ...
}

您不能在服务层上创建一个方法,接受
作为参数,并将
文件.InputStream
传递给它吗?流不需要任何与web相关的依赖项,您可以通过复制其他数据结构中的数据来使用它来避免复制内存。

您能告诉我们您的服务层的外观吗什么样子?
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);
    }
    ...
}