问题描述
您好,我正在尝试将一个简单的文本文件上传到 Azure 文件共享。
String ACCOUNT_NAME = "AccountName";
String shareServiceURL = String.format("https://%s.file.core.windows.net",ACCOUNT_NAME);
String directoryPath = "path in file storage";
String shareName = "my-share";
String fileName = "name-of-file-in-local.txt";
String localFilePath = "local-path-inserted-here";
ShareFileClient fileClient = new ShareFileClientBuilder()
.connectionString(CONNECTION_STRING)
.endpoint(shareServiceURL+fileName)
.shareName(shareName)
.resourcePath(localFilePath+fileName)
.buildFileClient();
/*Tried replacing above resourcePath params with directoryPath
and later with directoryPath + fileName.*/
//Finally trying to upload the file.
fileClient.uploadFromFile(localFilePath+fileName);
我不确定我错过了什么,没有收到任何异常或错误,但我在文件共享中没有看到该文件。我错过了什么吗?是否可以从 Azure SDK 获取错误代码以验证文件是否已放置。
解决方法
您可以使用此代码,并且您需要为您上传的文件指定合适的大小:
try
{
ShareDirectoryClient dirClient = new ShareFileClientBuilder()
.connectionString(connectStr).shareName(shareName)
.resourcePath(dirName)
.buildDirectoryClient();
ShareFileClient fileClient = dirClient.getFileClient(fileName);
fileClient.create(1024*100);
fileClient.uploadFromFile(localfile);
}
catch (Exception e)
{
System.out.println("uploadFile exception: " + e.getMessage());
}
更多细节可以参考这个官方文档:
需要注意这段代码中ShareFileClient.create
方法的使用: