简体   繁体   English

使用 SAS(共享访问签名)使用 Azure 存储上传文件

[英]Upload file with Azure Storage using SAS (Shared Access Signature)

I know that there is library available for uploading the file using Azure Storage.我知道有库可用于使用 Azure 存储上传文件。 I have refer this for same.我曾指为相同。

But, they have not give information for how to use SAS with that.但是,他们没有提供有关如何使用 SAS 的信息。 I have account name, and sas url for access and upload file there.我有帐户名和用于访问和上传文件的 sas url。 But I don't know how to use that for uploading file.但我不知道如何使用它来上传文件。

If I use above mention library it shows me invalid storage connection string because I am not passing the key in it (Which is not required with sas).如果我使用上面提到的库,它会显示无效的存储连接字符串,因为我没有在其中传递密钥(sas 不需要)。 So I am confused how I can upload file.所以我很困惑如何上传文件。

I have refer this documentation also for uploading file using sas.我也参考了这个文档来使用 sas 上传文件。 but not getting proper steps to do this.但没有采取适当的步骤来做到这一点。 They have made demo for their windows app.他们已经为他们的 Windows 应用程序制作了演示。 I want to have that in android with use of sas.我想在 android 中使用 sas。

Update更新

I have try with below code with reference to the console app made by Azure to check and access SAS.我参考Azure 制作控制台应用程序尝试使用以下代码来检查和访问 SAS。

 try {
        //Try performing container operations with the SAS provided.

        //Return a reference to the container using the SAS URI.
        //CloudBlockBlob blob = new CloudBlockBlob(new StorageUri(new URI(sas)));
        String[] str = userId.split(":");
        String blobUri = "https://myStorageAccountName.blob.core.windows.net/image/" + str[1] + "/story/" + storyId + "/image1.jpg" + sas.toString().replaceAll("\"","");
        Log.d(TAG,"Result:: blobUrl 1 : "+blobUri);
        CloudBlobContainer container = new CloudBlobContainer(new URI(blobUri));
        Log.d(TAG,"Result:: blobUrl 2 : "+blobUri);
        CloudBlockBlob blob = container.getBlockBlobReference("image1.jpg");
        String filePath = postData.get(0).getUrl().toString();
        /*File source = new File(getRealPathFromURI(getApplicationContext(),Uri.parse(filePath))); // File path
        blob.upload(new FileInputStream(source), source.length());*/
        Log.d(TAG,"Result:: blobUrl 3 : "+blobUri);
        //blob.upload(new FileInputStream(source), source.length());
        //blob.uploadText("Hello this is testing..."); // Upload text file
        Log.d(TAG, "Result:: blobUrl 4 : " + blobUri);
        Log.d(TAG, "Write operation succeeded for SAS " + sas);
        response = "success";
        //Console.WriteLine();
    } catch (StorageException e) {
        Log.d(TAG, "Write operation failed for SAS " + sas);
        Log.d(TAG, "Additional error information: " + e.getMessage());
        response = e.getMessage();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        response = e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        response = e.getMessage();
    } catch (URISyntaxException e) {
        e.printStackTrace();
        response = e.getMessage();
    } catch (Exception e){
        e.printStackTrace();
        response = e.getMessage();
    }

Now, when I upload text only it says me below error现在,当我只上传文本时,它会在错误下方显示我

Server failed to authenticate the request.服务器未能验证请求。 Make sure the value of Authorization header is formed correctly including the signature.确保 Authorization 标头的值形成正确,包括签名。

Now, my requirement is to upload Image file.现在,我的要求是上传图像文件。 So when I uncomment code for uploading image file it is not giving me any error but even not uploading image file.因此,当我取消注释上传图像文件的代码时,它没有给我任何错误,甚至没有上传图像文件。

@kumar kundal The mechanism that you have explained is completely right. @kumar kundal 你解释的机制是完全正确的。 Below is the more detailed answer about uploading profile image to the Azure Server.下面是关于将配置文件图像上传到 Azure 服务器的更详细的答案。

First create SAS url to upload Image(or any file) to blob storage:首先创建 SAS url 将图像(或任何文件)上传到 blob 存储:

String sasUrl = "";
// mClient is the MobileServiceClient
ListenableFuture<JsonElement> result = mClient.invokeApi(SOME_URL_CREATED_TO_MAKE_SAS, null, "GET", null);
Futures.addCallback(result, new FutureCallback<JsonElement>() {
        @Override
        public void onSuccess(JsonElement result) {
            // here you will get SAS url from server
            sasUrl = result; // You need to parse it as per your response
        }

        @Override
        public void onFailure(Throwable t) {
        }
    });

Now, you have sasURL with you.现在,您有了 sasURL。 That will be something like the below string:这将类似于以下字符串:

sv=2015-04-05&ss=bf&srt=s&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=F%6GRVAZ5Cdj2Pw4tgU7IlSTkWgn7bUkkAg8P6HESXwmf%4B

Now, you need to append the sas url with your uploading url.现在,您需要将 sas 网址附加到您的上传网址。 See below code in which I have appended the SAS url with my uploading request.请参阅下面的代码,其中我在上传请求中附加了 SAS url。

try {
        File source = new File(filePath); // File path
        String extantion = source.getAbsolutePath().substring(source.getAbsolutePath().lastIndexOf("."));
        // create unique number to identify the image/file.
        // you can also specify some name to image/file
        String uniqueID = "image_"+ UUID.randomUUID().toString().replace("-", "")+extantion; 
        String blobUri = MY_URL_TO_UPLOAD_PROFILE_IMAGE + sas.replaceAll("\"","");
        StorageUri storage = new StorageUri(URI.create(blobUri));
        CloudBlobClient blobCLient = new CloudBlobClient(storage);
        CloudBlobContainer container = blobCLient.getContainerReference("");
        CloudBlockBlob blob = container.getBlockBlobReference(uniqueID);
        BlobOutputStream blobOutputStream = blob.openOutputStream();
        byte[] buffer = fileToByteConverter(source);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
        int next = inputStream.read();
        while (next != -1) {
            blobOutputStream.write(next);
            next = inputStream.read();
        }
        blobOutputStream.close();
        // YOUR IMAGE/FILE GET UPLOADED HERE
        // IF YOU HAVE FOLLOW DOCUMENT, YOU WILL RECEIVE IMAGE/FILE URL HERE 
    } catch (StorageException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e){
        e.printStackTrace();
    }

I hope this information help you lot for uploading the file using blob storage.我希望这些信息对您使用 blob 存储上传文件有很大帮助。 Please let me know if you have any doubt apart from this.如果您对此有任何疑问,请告诉我。 I can help in that.我可以提供帮助。

您可以参考这篇文章https://azure.microsoft.com/zh-cn/documentation/articles/storage-configure-connection-string/以了解如何通过访问存储帐户中的资源时正确配置连接字符串共享访问签名(SAS)。

Uploading a pic to BLOB storage .将图片上传到BLOB存储 I got it after searching for hours .Take a look :-我在搜索了几个小时后得到了它。看看:-

Uploading the photo image is a multistep process:上传照片图像是一个多步骤的过程:

First you take a photo, and insert a TodoItem row into the SQL database that contains new meta-data fields used by Azure Storage.首先拍摄一张照片,然后将TodoItem行插入包含 Azure 存储使用的TodoItem数据字段的 SQL 数据库中。 A new mobile service SQL insert script asks Azure Storage for a Shared Access Signature (SAS) .新的移动服务 SQL 插入脚本要求 Azure 存储提供Shared Access Signature (SAS) That script returns the SAS and a URI for the blob to the client.该脚本将 SAS 和 blob 的 URI 返回给客户端。 The client uploads the photo, using the SAS and blob URI.客户端使用 SAS 和 blob URI 上传照片。

So what is a SAS ?那么什么是SAS呢?

It's not safe to store the credentials needed to upload data to the Azure Storage service inside your client app.在客户端应用程序中存储将数据上传到 Azure 存储服务所需的凭据是不安全的。 Instead, you store these credentials in your mobile service and use them to generate a Shared Access Signature (SAS) that grants permission to upload a new image.相反,您将这些凭据存储在您的移动服务中,并使用它们生成一个Shared Access Signature (SAS) ,授予上传新图像的权限。 The SAS , a credential with a 5 minute expiration, is returned securely by Mobile Services to the client app. SAS是一个有效期为 5 分钟的凭证,由移动服务安全地返回给客户端应用程序。 The app then uses this temporary credential to upload the image.然后应用程序使用此临时凭证上传图像。

for further queries and detail analysis.以便进一步查询和详细分析。 Visit this official documentation https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-upload-data-blob-storage/访问此官方文档https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-upload-data-blob-storage/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Java在android中使用sas url将文件上传到azure存储 - Upload file into azure storage using sas url in android using Java 使用共享访问签名从Android应用程序上的Azure表获取数据 - Get data from Azure Table on Android App using Shared Access Signature 使用SAS上传Android Azure Storage Blob; com.microsoft.azure.storage.StorageException:指定的资源不存在 - Android Azure Storage Blob upload with SAS; com.microsoft.azure.storage.StorageException: The specified resource does not exist 如何使用Android设备上的Azure SAS URL上载媒体(.mp4)文件 - How to upload media (.mp4) file using Azure SAS url from Android device 在Azure文件云存储上上传进度 - Upload With Progress on Azure File Cloud Storage 在Android中使用Azure存储获取上传进度 - Getting upload progress using Azure Storage in Android 如何在没有授予“存储”权限的情况下访问共享文件 - how to access shared file without grant permission for 'storage' 在Azure Android Storage SDK上上传Blob文件期间获得进度 - Get progress during blob file upload on Azure Android Storage SDK 使用Azure存储下载文件并使用简历下载 - Download file using Azure Storage with resume download 如何在简单的文件上传代码Button中使用Storage Access Framework? - how to use Storage Access Framework in a simple file upload code Button?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM