我正在尝试根据用户 ID 创建容器,并且在一个容器中我想将 5 个 blob 作为文本文件上传。客户端是 Windows 应用程序 (UWP)。
用户 ID 和文本文件被发送到发布请求 (webapi2) 并从这里创建容器并在其中上传文件。同时,容器名称被赋予服务总线队列,该队列应由工作角色读取。
下面是客户端代码:
foreach (StorageFile file in files)
{
filesListView.Items.Add(file.DisplayName);
IInputStream inputStream = await file.OpenAsync(FileAccessMode.Read);
HttpMultipartFormDataContent multipartContent = new HttpMultipartFormDataContent();
//if (i == false)
//{
multipartContent.Add(new HttpStringContent(txtbox.Text), "myText");
i = true;
// }
multipartContent.Add(new HttpStreamContent(inputStream), "myFile", file.Name);
HttpClient client = new HttpClient();
Uri uri = new Uri("http://localhost:35095/api/upload");
HttpResponseMessage response = await client.PostAsync(uri,multipartContent);
}
post 方法如下,其中还包括将容器名称发送到服务总线队列的功能。
foreach (HttpContent ctnt in prvdr.Contents)
{
// You would get hold of the inner memory stream here
Stream stream = ctnt.ReadAsStreamAsync().Result;
stream.Position = 0;
var type1 = ctnt.GetType();
if (ctnt.Headers.ContentDisposition.Name == "\"myFile\"")
{
var filename = ctnt.Headers.ContentDisposition.FileName;
var a = filename.Replace("\"", "");
CloudBlockBlob blob = imagesContainer.GetBlockBlobReference(a);
if (ctnt.Headers.ContentType != null)
{
// Set appropriate content type for your uploaded file
blob.Metadata["FileType"] = "Text";
blob.Properties.ContentType = ctnt.Headers.ContentType.MediaType;
}
// this.FileData.Add(new MultipartFileData(ctnt.Headers, blob.Name));
StreamReader rdr = new StreamReader(stream);
var a1 = rdr;
blob.UploadFromStream(stream);
}
else
{
string aaa = ctnt.Headers.ContentDisposition.ToString();
StreamReader rdr = new StreamReader(stream);
Container = rdr.ReadLine();
string z = Container;
imagesContainer = blobClient.GetContainerReference(z);
imagesContainer.CreateIfNotExists();
string msg = imagesContainer.Name;
sendMessage(msg);
}
}
});
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public void sendMessage(String containerName)
{
// getting connection string from App setting
var connString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
// creating service Bus
var namespaceManager = NamespaceManager.CreateFromConnectionString(connString);
if (!namespaceManager.QueueExists("testqueue"))
{
namespaceManager.CreateQueue("testqueue");
}
// creating service bus client
QueueClient clnt = QueueClient.CreateFromConnectionString(connString, "TestQueue");
string msg = containerName;
BrokeredMessage message = new BrokeredMessage(msg);
clnt.Send(message);
我成功地创建了容器、上传文本文件并将容器名称传递给服务总线队列。
问题如下;
- 从客户端,由于传递了两个数据(容器,即user-id及其对应的5个文本文件),else部分被执行了5次。
- 因为有 5 条消息(同一个容器)被发送到服务总线队列。
- 我只需要向队列发送一条消息,即容器名称。
任何帮助将不胜感激。我是 Azure 的新手。