azure function: set blob filename from http request

时间:2018-03-22 23:52:33

标签: azure azure-storage-blobs azure-functions

I am trying to set an azure function to upload a blob from an HTTP request to a blob.

I was able to use the following for uploading a file with a static filename:

public static class Uploader
{
    [FunctionName("Uploader")]
    public static IActionResult Run(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequest req,
    [Blob("hello/uploaded.jpg", FileAccess.Write)]Stream writer,
    TraceWriter log
    )
        {
            log.Info("trigger for image upload started...");
            if (!req.ContentType.Contains("multipart/form-data") || (req.Form.Files?.Count ?? 0) == 0)
            {
                log.Warning("no images found on upload attempt");
                return new BadRequestResult();
            }
            foreach (var file in req.Form.Files)
                file.CopyTo(writer.);

            return new OkObjectResult("Done!");
        }
}

Is there any way I could alter Blob("hello/uploaded.jpg") into something like Blob("hello/{fileName}" to get the name dynamically the HTTP request. I don't mind if it's anywhere from the head or body. I am trying to not use the whole GetBlockBlobReference process just for the dynamic file name alone.

Update I am not sure if I am missing something or looking at this problem the wrong way. For a serverless set up with a blob storage isn't an HTTP upload supposed to be an obvious and common scenario? How come there aren't any examples for this?

2 个答案:

答案 0 :(得分:3)

@RomanKiss建议的选项应该有用。或者,如果您愿意,可以将文件名放入功能URL模板中:

[FunctionName("Uploader")]
public static IActionResult Run(
  [HttpTrigger(AuthorizationLevel.Function, "post", Route = "uploader/{filename}")] 
  HttpRequest req,
  string filename,
  [Blob("hello/{filename}", FileAccess.Write)] Stream writer,
  TraceWriter log)
{
   //...
}

答案 1 :(得分:1)

以下是HttpRequestMessage和POCO绑定的示例:

[FunctionName("Uploader")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] Info input, HttpRequest req,
[Blob("hello/{FileName}", FileAccess.Write)]Stream writer,
TraceWriter log
)
{
   //...
}

public class Info
{
   public string FileName { get; set; }
   //...
}

更新

以下代码段显示了使用扩展的HttpTrigger绑定数据支持以及 headers query 等众所周知的属性的示例,更多详细信息here

[FunctionName("Uploader")]
public static IActionResult Run(
  [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)HtpRequest req,
  [Blob("hello/{query.filename}", FileAccess.Write)] Stream writer,
  // [Blob("hello/{headers.filename}", FileAccess.Write)] Stream writer,
  TraceWriter log)
{
   //...
}

网址样本:
http://localhost:7071/api/Uploader?filename=uploaded.jpg