C# .net 4.8 Razor:将文件从本地磁盘复制到Azure Blob

h43kikqp  于 2023-08-07  发布在  C#
关注(0)|答案(1)|浏览(98)

我仍然在努力解决下面这个让我发疯的问题。我正在尝试将C# webapp中的文件从本地磁盘复制到Azure Blob存储。当我从Azure运行程序时,程序尝试从服务器磁盘复制文件,而不是从先前从网页中选择的本地客户端磁盘复制文件。找到这个对我来说是一件相当痛苦的事情,因为没有错误信息。到现在为止。在代码示例中,您可以看到我正在尝试做什么。
通常,该文件应该通过HttpPostedFileBase可用。顺便说一句,“ActionResult Upload(...)”对我也不起作用,它只通过“ActionResult Index(...)”起作用。
有没有人以前做过这个,可以告诉我我做错了什么?请不要在谜语写,我需要一个代码的例子,如果可能的确切答案。提前感谢帮助我的人。
为了测试,我已经将函数减少到绝对必要的程度。

**Razor html** ---------------------------------------
<form method="post" enctype="multipart/form-data">
   <input type="file" name="file" />
   <button type="submit">Upload File</button>
</form>

**cSharp** -------------------------------------------
using Microsoft.Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.Web.Mvc;
using System.Web;
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Microsoft.AspNetCore.Http;

//other code ......
   
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) //IFormFile ?
{
    string containerName = "fileupload";
    string connectionString = Def...=https;A..Name=st..e;A..Key=....Z==;End..x=core.windows.net";

    if (file != null && file.ContentLength > 0)
    {
        var uploadedFile = Request.Files[0];
        var newFileName = DateTime.Now.ToString("yyyyMMdd_HH-mm-ss") + "_" + myCountry + "_" + file.FileName;
        BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
        BlobContainerClient containerClient = new BlobContainerClient(connectionString, containerName);
        BlobClient blobClientF = containerClient.GetBlobClient(newFileName);
        FileStream filestream = new FileStream(Path.GetFileName(uploadedFile.FileName), FileMode.OpenOrCreate);
        blobClientF.UploadAsync(filestream, true);
    }

    return View();
}

字符串

oo7oh9g9

oo7oh9g91#

我尝试了下面的代码,可以用C# webapp将文件上传到我的存储帐户容器。

验证码:
Program.cs:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
    name: "upload",
    pattern: "Home/UploadFile",
    defaults: new { controlle = "home", action = "uploadFile" });

app.Run();

字符串

Controllers/HomeController.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Azure.Storage.Blobs;
using System;
using System.IO;
using System.Threading.Tasks;
using WebApplication8.Models;

namespace WebApplication8.Controllers
{
    public class HomeController : Controller
    {
        private readonly IConfiguration _configuration;
        public HomeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file != null && file.Length > 0)
            {
                string containerName = "kamcontainer"; 
                string connectionString = _configuration.GetConnectionString("AzureStorage");

                var newFileName = DateTime.Now.ToString("yyyyMMdd_HH-mm-ss") + "_" + file.FileName;
                BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
                BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

                BlobClient blobClient = containerClient.GetBlobClient(newFileName);
                using (var stream = file.OpenReadStream())
                {
                    await blobClient.UploadAsync(stream, true);
                }
            }

            return RedirectToAction("Index");
        }
        // Handle errors and display a user-friendly error page when an exception occurs
        // ResponseCache with explicit values
    

> [ResponseCache (Duration = 0, Location = ResponseCacheLocation.None,
> NoStore = true)]

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = System.Diagnostics.Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}


ResponseCache位置和持续时间参考

浏览次数/首页/index.cshtml:

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

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

appsettings.json:

{
  "ConnectionStrings": {
    "AzureStorage": "<storage_account_connec_string>"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

项目结构:

x1c 0d1x的数据

输出:

成功运行如下,



它在浏览器中打开,如下所示,然后我点击选择文件选项,选择一个我要上传为blob的文件,



我选择了一个文件,点击【上传文件】,如下所示:


  • 然后,文件作为blob上传到Azure Portal中的存储帐户容器,如下所示,*

我已经上传了三个文件到下面的容器,
x1c4d 1x的

相关问题