【问题标题】:Convert a path (which is an image) to HttpPostedFileBase将路径(即图像)转换为 HttpPostedFileBase
【发布时间】:2020-09-29 09:18:34
【问题描述】:

我为用户提供上传图片。

但是如果不做的话,我想在一个图像文件夹中设置一个默认图像。

如何将“HttpPostedFileBase”类型的模型属性设置为位于我以编程方式设置的路径的图像?

模型属性:

 public HttpPostedFileBase UploadedImage { get; set; }

我尝试了这些,但没有成功。

我得到的这个:无法将类型“字符串”转换为“System.Web.HttpPostedFileBase”。

 if (userProfileForSaveVM.UserProfileSingleVM.UploadedImage == null)
 {
   // Set a default.
   userProfileForSaveVM.UserProfileSingleVM.UploadedImage = 
   "F:\\GbngWebClient\\GbngWebClient\\Images\\Avatar.png";
 }

我得到的这个:属性或索引器“HttpPostedFileBaseInputStream”不能分配给——它是只读的。

 if (userProfileForSaveVM.UserProfileSingleVM.UploadedImage == null)
 {
   // Set a default.
   String pathImage = Server.MapPath("F:\\GbngWebClient\\GbngWebClient\\Images\\Avatar.png");
   userProfileForSaveVM.UserProfileSingleVM.UploadedImage.InputStream = new FileStream(pathImage, FileMode.Open);
 }

我得到的这个:无法将类型 'byte[]' 转换为 'System.Web.HttpPostedFileBase'。

 if (userProfileForSaveVM.UserProfileSingleVM.UploadedImage == null)
 {
   // Set a default.
   byte[] imageArray = 
   System.IO.File.ReadAllBytes(@F:\\GbngWebClient\\GbngWebClient\\Images\\Avatar.png");
   userProfileForSaveVM.UserProfileSingleVM.UploadedImage = imageArray;
 }

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    我不确定您为什么要创建这种类型的类。该类用于从 HTTP 请求接收文件数据。通常,您使用它的输入流这个类获取数据。 msdn 文档在这里有一个示例:

    https://docs.microsoft.com/en-us/dotnet/api/system.web.httppostedfile.inputstream?view=netframework-4.8#System_Web_HttpPostedFile_InputStream

    您要做的是从 HttpPostedFileClass 获取文件流,如果没有,则从您的默认位置获取该文件流。您可以声明一个空的内存流作为开始,并在适当的情况下从 HttpPostedFile 或本地资源填充该流。

    【讨论】:

      【解决方案2】:

      尝试在 View 中使用 check null :

      if (userProfileForSaveVM.UserProfileSingleVM.UploadedImage != null)
      {
         <img src= "@Url.Content("~/uploads/FileUpload12011_03_02_11_49_22.jpg")" alt="IMAGES" />
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-14
        • 2017-05-11
        • 2020-12-14
        • 2021-11-09
        • 1970-01-01
        • 1970-01-01
        • 2011-12-12
        相关资源
        最近更新 更多