【问题标题】:How can I post image from UWP to .NET core web api?如何将图像从 UWP 发布到 .NET 核心 Web api?
【发布时间】:2018-10-12 03:01:51
【问题描述】:

现在我已经为使用 HttpClient 的 Web api 部分配置了 UWP 照片发布。

Uri uri = new Uri("http://localhost:50040/api/Upload");
IInputStream inputStream = await photoFile.OpenAsync(FileAccessMode.Read);
HttpMultipartFormDataContent multipartContent = new HttpMultipartFormDataContent();
multipartContent.Add(new HttpStreamContent(inputStream), "myFile", photoFile.Name);
Windows.Web.Http.HttpClient newclient = new Windows.Web.Http.HttpClient();
Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(uri, multipartContent);

但我不知道如何设置服务器端,即我的 .NET 核心 web api,以获取从我的 UWP 应用程序发布的图像。请帮助我,谢谢。

【问题讨论】:

    标签: c# .net uwp http-post asp.net-core-webapi


    【解决方案1】:

    但我不知道如何设置服务器端,即我的 .NET core web api

    请参考File uploads official tutorial 来创建您的服务器端。例如,添加 POST 方法,如以下示例代码所示,以使用上面显示的客户端代码接收 UWP 客户端发送的文件。

    // POST api/values
    [HttpPost]
    public async Task<IActionResult> Post(IFormFile myFile)
    {
       // full path to file in temp location, you could change this
       var filePath = Path.GetTempFileName();
       if (myFile.Length > 0)
       {
           using (var stream = new FileStream(filePath, FileMode.Create))
           {
               await myFile.CopyToAsync(stream);
           }
       }
       // process uploaded files
       // Don't rely on or trust the FileName property without validation.
       return Ok(new { filePath, myFile.Length });
    }
    

    更多细节您也可以参考official sample。

    【讨论】:

    • 当我使用它尝试时,当我尝试使用邮递员将图像发布到我的网络 api 时,它说 http 500 内部错误。
    • @xiaozhi,我不知道你是怎么发帖的。但是这段代码 sn-p 确实对我有用。您需要提供整个服务器端代码和邮递员屏幕截图让我帮助跟踪。
    【解决方案2】:

    在 Web API 控制器中

    public IHostingEnvironment _environment;
    public UploadFilesController(IHostingEnvironment environment) // Create Constructor 
    {
        _environment = environment;
    }
    
    [HttpPost("UploadImages")]
    public Task<ActionResult<string>> UploadImages([FromForm]List<IFormFile> allfiles)
    {
        string filepath = "";
        foreach (var file in allfiles)
        {
            string extension = Path.GetExtension(file.FileName);
            var upload = Path.Combine(_environment.ContentRootPath, "ImageFolderName");
            if (!Directory.Exists(upload))
            {
                Directory.CreateDirectory(upload);
            }
            string FileName = Guid.NewGuid() + extension;
            if (file.Length > 0)
            {
                using (var fileStream = new FileStream(Path.Combine(upload, FileName), FileMode.Create))
                {
                    file.CopyTo(fileStream);
                }
            }
            filepath = Path.Combine("ImageFolderName", FileName);
        }
        return Task.FromResult<ActionResult<string>>(filepath);
    }
    

    在你的page.xaml.cs中

    using Windows.Storage;
    using Windows.Storage.Pickers;
    .....
    StorageFile file;
    ......
    
    private async void btnFileUpload_Click(object sender, RoutedEventArgs e) // Like Browse button 
    {
        try
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".png");
            file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                //fetch file details
            }
        }
        catch (Exception ex)
        {
    
        }
    }
    
    //When upload file
    var http = new HttpClient();
    var formContent = new HttpMultipartFormDataContent();
    var fileContent = new HttpStreamContent(await file.OpenReadAsync());
    formContent.Add(fileContent, "allfiles", file.Name);
    var response = await http.PostAsync(new Uri("Give API Path" + "UploadImages", formContent);
    string filepath = Convert.ToString(response.Content); //Give path in which file is uploaded
    

    希望这段代码对您有所帮助...

    但请记住formContent.Add(fileContent, "allfiles", file.Name); 这一行很重要,allfiles 是在 web api 方法 "public Task&lt;ActionResult&lt;string&gt;&gt; UploadImages([FromForm]List&lt;IFormFile&gt; **allfiles**)" 中获取文件的参数名称

    谢谢!!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 2020-09-07
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 2017-01-05
      相关资源
      最近更新 更多