无法将“Microsoft.Asp.NetCore.Http.FormFile”类型的对象转换为在 Asp.NetCore MVC Web 应用程序中键入“System.IO.Stream”

Posted

技术标签:

【中文标题】无法将“Microsoft.Asp.NetCore.Http.FormFile”类型的对象转换为在 Asp.NetCore MVC Web 应用程序中键入“System.IO.Stream”【英文标题】:Unable to cast object of type 'Microsoft.Asp.NetCore.Http.FormFile' to type 'System.IO.Stream' in Asp.NetCore MVC web app 【发布时间】:2021-06-07 15:51:17 【问题描述】:

我是 Asp.netCore 和 Microsoft Azure 的新手。最近,我正在尝试将 ASP.net Core MVC Web 应用与 Blob 存储集成。

在应用程序中,我将文件(图像)上传到 azure blob 存储,上传文件的 URL 存储在 Microsoft SQL 数据库中。数据库已完美连接到应用程序,并且工作正常。 我已经创建了一个 Azure blob 存储,并且我已经创建了容器并将文件手动上传到 blob 存储。 Blob 存储也可以完美运行。

这是控制器类:(出于测试目的,我已将图像上传控制器放在“HomeController”中

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using WebAppMVC.Data;
using WebAppMVC.Models;
using WebAppMVC.Utilities;

namespace WebAppMVC.Controllers

public class HomeController : Controller

    private readonly UserManager<WebAppMVCUser> _userManager;
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger,UserManager<WebAppMVCUser> userManager)
    
        _logger = logger;

        /* newly added */
        _userManager = userManager;
        utility = new BlobUtility(accountName, accountKey);
        db = new WebAppMVC_DBContext();
        /* newly added */
    

    /* newly added */
    BlobUtility utility;
    WebAppMVC_DBContext db;
    string accountName = "_my_Storage_Name";
    string accountKey = "My_storage_account_key";
    /* newly added */

    [Authorize]
    public IActionResult Index()
    
        /* newly added */
        string loggedInUserId = _userManager.GetUserId(User);
        List<UserMedium> userMedia = (from a in db.UserMedia where a.UserId.ToString() == loggedInUserId select a).ToList();
        ViewBag.PhotoCount = userMedia.Count;
        return View(userMedia);
        /* newly added */
    

    /* newly added */
    [Authorize]
    public ActionResult DeleteImage(int id)
    
        UserMedium userImage = db.UserMedia.Find(id);
        db.UserMedia.Remove(userImage);
        db.SaveChanges();
        string BlobNameToDelete = userImage.ImageUrl.Split('/').Last();
        utility.DeleteBlob(BlobNameToDelete, "profilepics");
        return RedirectToAction("Index");
    

    [Authorize]
    [HttpPost]
    public ActionResult UploadImage(IFormFile file)
    
        if (file != null)
        
            string ContainerName = "profilepics"; // container name. 
            //file = Request.File["file"];
            string fileName = Path.GetFileName(file.FileName);
            Stream imageStream = file.OpenReadStream();
            var result = utility.UploadBlob(fileName, ContainerName, (Stream)file);
            if (result != null)
            
                string loggedInUserId = _userManager.GetUserId(User);
                UserMedium usermedium = new UserMedium();
                usermedium.MediaId = new Random().Next();
                try
                 
                    usermedium.UserId = Int32.Parse(loggedInUserId);
                
                catch
                
                    Console.WriteLine($"Unable to parse 'loggedInUserId'");
                
                usermedium.ImageUrl = result.Uri.ToString();
                db.UserMedia.Add(usermedium);
                db.SaveChanges();
                return RedirectToAction("Index");
            
            else
            
                return RedirectToAction("Index");
            
        
        else
        
            return RedirectToAction("Index");
        
    
    /* newly added */

    [Authorize]
    public IActionResult Privacy()
    
        return View();
    
    [Authorize]
    public IActionResult Media()
    
        return View();
    

    public IActionResult InformationPortal()
    
        return View();
    

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    
        return View(new ErrorViewModel  RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier );
    


这是查看 Index.cshtml 代码:(我正在从 Index.cshtml 上传文件)Uploading-Image-from-the-view

@model IEnumerable<WebAppMVC.Models.UserMedium>
<div class="container">

<div class="row">
    @using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new  enctype = "multipart/form-data" ))
    
        <div class="panel panel-warning">
            <div class="panel-heading">
                <h3 class="panel-title">Upload and save your photo</h3>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-4 col-md-offset-4">
                        <input type="file" name="file" />
                        <br />
                        <input type="submit" class="btn btn-warning form-control" value="Save Photo" />
                    </div>
                </div>
            </div>
        </div>
    

</div>

<br />

<div class="row">
    <div class="col-lg-12">

        <div class="alert alert-warning">You have @ViewBag.PhotoCount Photos </div>
    </div>
    @foreach (var item in Model)
    
        <div class="col-lg-3 col-md-4 col-xs-6 thumb">

            <a class="thumbnail" href="@item.ImageUrl">
                <img class="img-responsive" src="@item.ImageUrl" style="height: 300px;width:100%;" >
            </a>
            <a href="@Url.Action("DeleteImage", "Home",new  id = item.MediaId )" class="btn btn-default btn-block">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
            </a>

        </div>
    

</div>

但是当我运行应用程序时,上传文件(jpg 图像)后,我收到以下异常: 这个异常来了,应用程序也进入了中断模式。

例外: Click-here-to-see-the-exception

如图所示,应用程序进入中断模式,并在 HomeController(我用来控制文件上传的控制器)的 74 行抛出异常。

以下是异常的详细描述:exception-details

当我向前走时,我在浏览器上收到此错误消息:Exception-error-on-browser

我不明白这个错误,有人知道如何解决这个问题吗? 提前致谢。

【问题讨论】:

【参考方案1】:

试试这个函数将 IFormFile 转换为 Stream。

    public static async Task<Stream> GetStream(this IFormFile formFile)
    
        using (var memoryStream = new MemoryStream())
        
            await formFile.CopyToAsync(memoryStream);
            return memoryStream;
        
    

【讨论】:

【参考方案2】:

这对你有用:

IFormFile file;
byte[]? image = Array.Empty<byte>();

if (file != null)

    await using var memoryStream = new MemoryStream();
    await file!.CopyToAsync(memoryStream);
    image = memoryStream.ToArray();

【讨论】:

以上是关于无法将“Microsoft.Asp.NetCore.Http.FormFile”类型的对象转换为在 Asp.NetCore MVC Web 应用程序中键入“System.IO.Stream”的主要内容,如果未能解决你的问题,请参考以下文章

为啥我无法正确获取图像数据或无法将数据发送到服务器?

无法将 createdAt 和 updatedAt 保存为日期时间值,也无法将后端保存为前端

C# 无法将类型为“System.Byte[]”的对象强制转换为类型“System.Data.DataTable

无法将类型为“System.Collections.Generic.List`1[EPMS.Domain.SingleItem]”的对象强制转换为类型“EPMS

无法将 .json 文件从 CSV 下载到 JSON 转换并且无法将 JSON 转换为 CSV

无法将 ReactiveUI 添加到 NUnit 测试项目