【问题标题】:How to upload image with other form control (Angular 8) and asp.net core api如何使用其他表单控件(Angular 8)和 asp.net core api 上传图像
【发布时间】:2020-08-02 20:57:40
【问题描述】:
        I want fill form which have upload profile image and other controls like Name,address 
        I am using angular 8 for client side and asp.net core for backend..
        I want viewmodel which contains all properties.

我已经使用 angular8 在 formdata 中上传图像。我经历了https://www.techiediaries.com/angular-formdata/.My 主要问题是如何在 ViewModel 中而不是在 httpRequest.Form.Files["ImageFile"] 中接收上传的文件

[HttpPost("Create")]
public IActionResult CreateApplication(ApplicationModel model)
 {
         //want to capture uploaded image 
            return Ok();
  }

【问题讨论】:

标签: asp.net angular asp.net-core


【解决方案1】:

看这个教程,会很有帮助:Click

这是我的做法:

[HttpPost]       
    public async Task<IActionResult> AddBodyType([FromForm]ApplicationModel model)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            else
            {
                var file = Request.Form.Files[0];
                var folderName = Path.Combine("Resources", "Images");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                if (file.Length > 0)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    var fullPath = Path.Combine(pathToSave, fileName);
                    var dbPath = Path.Combine(folderName, fileName);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                        await stream.FlushAsync();
                    }

                    model.ImagePath = dbPath;
                    await _context.Add(model);

                    return Ok();
                }
                else
                {
                    return BadRequest();
                }
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex}");
        }
    }

【讨论】:

  • 我的模型包含模型集合。例如 public class public class ApplicationModel{ public ApplicationDetails applicationDetails{get;set;} public ApplicationDetails applicationDetails{get;set;} } [FromFile] 如何工作
【解决方案2】:

好的,问题是目录名称不固定,它们是由新创建的产品ID创建的,因此解决方案是检查目录,如果不存在,则创建它.

例如

if (!Directory.Exists(folderName))
{
    Directory.CreateDirectory(folderName);
}

使用新 ID 创建后,即可使用/找到它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2021-08-19
    • 2020-04-08
    • 2020-03-15
    • 2017-11-01
    相关资源
    最近更新 更多