我尝试将文件上传到Azure上的云存储,但只获得bad request 400
响应。在本地主机上运行应用程序并尝试连接到Azure上的帐户。
当我把它放在try / catch中时,我在最后一行得到bad request 400
cloudFile.Create(档案大小);
下面的这一行返回null,但是当我在if语句中检查它时文件共享是否存在:
var listShares = fileClient.ListShares(); // null
我只找到了一个关于如何实际上传文件的示例:
// Connect to Azure Storage
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("AzureStorageConnectionString"));
//Create a CloudFileClient object for credentialed access to File storage.
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
//Get a reference to the file share we created previously.
CloudFileShare share = fileClient.GetShareReference("appbackup");
var listShares = fileClient.ListShares();
//Ensure that the share exists.
if (share.Exists())
{
//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
//Get a reference to the sampledir directory we created previously.
CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("sampledir");
//Ensure that the directory exists.
if (sampleDir.Exists())
{
var test = rootDir.ListFilesAndDirectories();
var Credentials = new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("accountName", "keyValue");
string stringUri = storageAccount.FileStorageUri.PrimaryUri + share.Name + "/sampledir/";
Uri theUri = new Uri(stringUri);
CloudFile cloudFile = new CloudFile(theUri, Credentials);
System.IO.FileInfo fi = new System.IO.FileInfo(filepath);
long fileSize = fi.Length;
cloudFile.Create(fileSize);
}
}
答案 0 :(得分:1)
我相信您的代码存在问题:
string stringUri = storageAccount.FileStorageUri.PrimaryUri + share.Name + "/sampledir/";
您未将文件名添加到stringUri
。请尝试将文件名添加到stringUri
,这应该可以解决问题。
答案 1 :(得分:0)
好吧我挣扎了好几年,因为我找不到好样品。最终我发现它很简单,你不会相信它。
以下内容不是从文件上传,而是从流中上传,所以我确定您可以加入点来弄清楚如何获取文件的流并使用它。
private static void CreateSampleFile(CloudFileDirectory sampleDir, string fileName)
{
CloudFile file = sampleDir.GetFileReference(fileName);
using (Stream s = GenerateStreamFromString(string.Format("It is {0}", DateTime.Now)))
{
file.UploadFromStream(s);
}
}
让我失望的关键是在包含文件夹上调用GetFileReference。你调用它,然后UploadFromStream为你完成剩下的工作。 GenerateStreamFromString()方法是关于如何将字符串转换为流的另一个问题的答案,并且与此问题无关。