You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC (.NET 4.8) Razor页面本地文件上传至Azure Blob存储路径错误问题求助

ASP.NET MVC (.NET 4.8) Razor页面本地文件上传至Azure Blob存储路径错误问题求助

Hey Michael, I totally get how frustrating this must be—nothing’s worse than a silent failure that only pops up once you deploy to Azure. Let’s break down what’s going wrong and fix it with a concrete code example.

The Core Problem

Your current code is trying to open a file from the server’s local disk using FileStream(Path.GetFileName(uploadedFile.FileName), ...), but the file the user uploaded doesn’t exist on the server—it’s only available in memory via the HttpPostedFileBase object’s InputStream. That’s why it works locally (by accident, if the file happens to exist on your dev machine) but breaks in Azure.

Fixes & Corrected Code

First, let’s clean up your code and fix the critical issues:

1. Updated Razor View (optional: switch to Upload action)

If you want to use an Upload action instead of Index, just add the action attribute to your form. If sticking with Index is fine, you can keep your original form:

<form method="post" enctype="multipart/form-data" action="@Url.Action("Upload")">
    <input type="file" name="file" />
    <button type="submit">Upload File</button>
</form>

2. Corrected C# Controller Code

I’ve fixed the stream handling, removed conflicting namespaces, and made the action properly async (since Azure Blob methods are async):

using Microsoft.Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.Web.Mvc;
using System.Web;
using System;
using System.IO;

// 移除Microsoft.AspNetCore.Http命名空间——它属于ASP.NET Core,不适用于.NET Framework MVC

public class YourControllerName : Controller
{
    // 如果想用Upload作为提交目标Action
    [HttpPost]
    public async Task<ActionResult> Upload(HttpPostedFileBase file)
    {
        string containerName = "fileupload";
        string connectionString = "你的Azure存储连接字符串"; // 替换为实际连接字符串

        // 确保myCountry已定义(比如从Session、用户数据中获取)
        string myCountry = "CN"; // 示例值,根据你的业务逻辑替换

        if (file != null && file.ContentLength > 0)
        {
            // 生成唯一文件名
            var newFileName = $"{DateTime.Now:yyyyMMdd_HH-mm-ss}_{myCountry}_{file.FileName}";

            // 初始化Blob客户端
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
            
            // 确保容器存在(可选但更安全)
            await containerClient.CreateIfNotExistsAsync(PublicAccessType.Blob);

            // 获取目标Blob的引用
            BlobClient blobClient = containerClient.GetBlobClient(newFileName);

            // 直接从上传文件的输入流上传到Blob——无需保存到服务器磁盘!
            await blobClient.UploadAsync(file.InputStream, new BlobUploadOptions
            {
                HttpHeaders = new BlobHttpHeaders
                {
                    ContentType = file.ContentType // 保留原始文件的MIME类型
                }
            });
        }

        return RedirectToAction("Index"); // 或返回你需要的视图
    }

    // 如果仍想使用Index作为提交目标Action
    [HttpPost]
    public async Task<ActionResult> Index(HttpPostedFileBase file)
    {
        // 复制上面Upload方法里的逻辑即可
        return View();
    }
}

Key Changes Explained

  • 移除Request.Files[0]: 你已经通过Action参数拿到了file对象,不需要再直接访问Request集合。
  • 使用file.InputStream: 这是用户上传文件的内存流,我们直接用它上传到Azure Blob,无需保存到服务器磁盘(既节省空间又避免路径问题)。
  • 改为异步Action: Azure的UploadAsync是异步方法,使用async Task<ActionResult>可以避免阻塞线程。
  • 添加CreateIfNotExistsAsync: 确保Blob容器存在,避免因容器未创建导致的上传失败。
  • 设置ContentType: 保留原始文件的MIME类型,方便后续下载时识别文件类型。
  • 清理冲突命名空间: Microsoft.AspNetCore.Http属于ASP.NET Core,和.NET Framework MVC不兼容,移除后可避免和IFormFile混淆。

为什么之前Upload Action无效?

如果之前尝试Upload Action失败,大概率是因为表单没有指定action属性——默认会提交到当前页面的Index Action。添加action="@Url.Action("Upload")"即可解决这个问题。

如果运行这段代码还有问题,随时告诉我,这应该能彻底解决“服务器磁盘找文件”的错误!

备注:内容来源于stack exchange,提问作者Michael 7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 07:59:39