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

前端之家收集整理的这篇文章主要介绍了上传文件并发送到服务层,即c#类库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试上传文件并将其发送到服务层进行保存,但是我一直在寻找控制器如何获取HTTPPostedFileBase并将其直接保存在控制器中的示例.我的服务层在web dll上没有依赖关系,因此我需要将我的对象读入内存流/字节吗?关于我应该怎么做的任何指示非常感谢…

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

码:

  1. public ActionResult UploadFile(string filename,HttpPostedFileBase thefile)
  2. {
  3. //what do I do here...?
  4.  
  5.  
  6. }

编辑:

  1. public interface ISomethingService
  2. {
  3. void AddFileToDisk(string loggedonuserid,int fileid,UploadedFile newupload);
  4. }
  5. public class UploadedFile
  6. {
  7. public string Filename { get; set; }
  8. public Stream TheFile { get; set; }
  9. public string ContentType { get; set; }
  10. }
  11.  
  12. public class SomethingService : ISomethingService
  13. {
  14. public AddFileToDisk(string loggedonuserid,UploadedFile newupload)
  15. {
  16. var path = @"c:\somewhere";
  17. //if image
  18. Image _image = Image.FromStream(file);
  19. _image.Save(path);
  20. //not sure how to save files as this is something I am trying to find out...
  21. }
  22. }

解决方法

您可以使用已发布文件InputStream属性内容作为字节数组读取,并将其与服务层可能需要的其他信息(如 ContentTypeFileName)一起发送到服务层:
  1. public ActionResult UploadFile(string filename,HttpPostedFileBase thefile)
  2. {
  3. if (thefile != null && thefile.ContentLength > 0)
  4. {
  5. byte[] buffer = new byte[thefile.ContentLength];
  6. thefile.InputStream.Read(buffer,buffer.Length);
  7. _service.SomeMethod(buffer,thefile.ContentType,thefile.FileName);
  8. }
  9. ...
  10. }

猜你在找的C#相关文章