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

Har*_*oon 6 c# asp.net-mvc

我想上传一个文件并将其发送到服务层保存,但是我一直在寻找的控制器如何获取HTTPPostedFileBase例子,在控制器中直接将其保存.我的服务层在web dll上没有依赖关系,因此我需要将我的对象读入内存流/字节吗?关于我应该怎么做的任何指示非常感谢...

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

码:

   public ActionResult UploadFile(string filename, HttpPostedFileBase thefile)
{
//what do I do here...?


}
Run Code Online (Sandbox Code Playgroud)

编辑:

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...
  } 
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 12

您可以使用的InputStream张贴文件的属性来读取其中的内容为一个字节数组,并将其发送给服务层与其他信息,如沿的ContentType文件名,你的服务层可能需要:

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);
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)