1

我一直在尝试将文件上传到Azure 存储容器。当我在本地运行我的网络应用程序时,如果文件不在网站根目录中,我会收到错误消息

Could not find file 'C:\Program Files (x86)\IIS Express\test.txt'.

如果我将文件复制web 应用程序根文件夹,它工作正常。

上运行Web 应用程序时出现错误

Could not find file 'D:\Windows\system32\test.txt'.

我无法从HttpPostedFileBase对象获取完整的本地文件路径。

代码:_

private string UploadFile(HttpPostedFileBase file, string folder)
    {
        try
        {
            var date = DateTime.UtcNow.ToString("yyyyMMdd-hhmmss-");
            var fileName = Path.GetFileName(file.FileName);

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=test;AccountKey=asdfasfasdasdf");
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); 
            CloudBlobContainer container = blobClient.GetContainerReference(folder);
            bool b = container.CreateIfNotExists();

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(date + fileName);
            blockBlob.Properties.ContentType = file.ContentType;

            using (var fileStream = System.IO.File.OpenRead(fileName))
            {
                blockBlob.UploadFromStream(fileStream);
            }
            return blockBlob.Uri.AbsoluteUri;

        }
        catch (Exception ex)
        {
            return ex.Message;
        }
4

2 回答 2

3

HttpPostedFileBase 手册有这样的说法;

FileName 获取客户端上文件的完全限定名。

也就是说,文件名不是可以在服务器上打开的。

我认为您真正想要做的是使用InputStream 属性

blockBlob.Properties.ContentType = file.ContentType;

blockBlob.UploadFromStream(file.InputStream);  // Upload from InputStream
return blockBlob.Uri.AbsoluteUri;
于 2013-03-17T07:16:31.037 回答
2

非常感谢:Joachim Isaksson(上图)昨天我花了一整天的时间与这一行代码作斗争。我已经对您的答案投了赞成票,但我想我现在应该在我自己的代码中添加您的解决方案的副本:

public async Task<ActionResult> UploadAsync()
{
    try
    {
        HttpFileCollectionBase files = Request.Files;
        int fileCount = files.Count;

        if (fileCount > 0)
        {
            for (int i = 0; i < fileCount; i++)
            {
                CloudBlockBlob blob = blobContainer.GetBlockBlobReference(GetRandomBlobName(files[i].FileName));

                blob.Properties.ContentType = files[i].ContentType;
                blob.UploadFromStream(files[i].InputStream);

                // the above 2 lines replace the following line from the downloaded example project:
                //await blob.UploadFromFileAsync(Path.GetFullPath(files[i].FileName), FileMode.Open);
            }
        }
        return RedirectToAction("Index");
    }
}
于 2017-02-21T06:56:49.207 回答