UploadFromFileAsync(字符串路径)抛出异常找不到您的位置

时间:2019-05-03 10:55:50

标签: c# azure .net-core

我正在使用UploadFromFileAsync(@“ E:\ test.html”);当发布路径时,抛出异常提示找不到位置,文件存在于我的路径中 谁能帮我

fileName = @"E:\\test.html"; 
cloudFile = fileDirectory.GetFileReference(fileName); // Upload a file to the share. 
await cloudFile.UploadFromFileAsync(fileName);
cloudFile.Metadata.Add("FileName", cloudFile.Name); 
cloudFile.Metadata.Add("Status", "1");
await cloudFile.SetMetadataAsync(); 

1 个答案:

答案 0 :(得分:0)

如果它是一个像webjobs一样在azure中运行的控制台项目,我不认为您可以将文件从本地系统上传到azure存储。因为它正在蔚蓝中运行并且不知道本地路径。

如果它是.net核心Web项目,例如mvc项目,则可以使用IFormFile,它允许用户从本地选择文件。

示例代码如下:

在controller.cs中(这里,我创建一个ImagesController.cs):

    public class ImagesController : Controller
    {

        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Index(IFormFile file)
        {

            if (file == null || file.Length == 0) return Content("file not selected");
            var filename = Path.GetFileName(file.FileName);
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("xx", "xxxx"), true);
            CloudBlobClient client = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer blobContainer = client.GetContainerReference("container_name");
            await blobContainer.CreateIfNotExistsAsync();
            var blockblob = blobContainer.GetBlockBlobReference(filename);

            using (var stream = file.OpenReadStream())
            {
                await blockblob.UploadFromStreamAsync(stream);
            }

            return View();
        }
}

然后在视图中,例如Index.cshtml

@{
    ViewData["Title"] = "Index";
}

<html>
<head>
    <title>upload files</title>
</head>
<body>
    <form asp-controller="Images" asp-action="Index" method="post"
          enctype="multipart/form-data">

        <input type="file" name="file" />
        <button type="submit">Upload File</button>
    </form>
</body>
</html>