【问题标题】:How to upload a file in angular如何以角度上传文件
【发布时间】:2021-07-02 23:38:09
【问题描述】:

我是 Angular CLI 的新手,我想创建一个文件上传器。就我而言,我需要将文件存储在应用程序的文件夹中,而不是在它之外。我查看了网络,但找不到任何信息。准确地说,我想将它们存储在资产文件夹 assets/media
我该怎么做?

【问题讨论】:

  • 如果您希望您的 Angular 应用能够上传文件,您需要一个后端服务器,处理该请求并将文件写入磁盘。

标签: angular file-upload


【解决方案1】:

我有这样的事情: html

<div class="col-md-12">
<input type="file" accept=".pdf, .txt" #file placeholder="Choose file" (change)="uploadFile(file.files)" style="display:none;">
<button style="width: 350px" type="button" class="btn btn-success" (click)="file.click()">Dodaj plik</button>

js

public uploadFile = (files) => {
if (files.length === 0) {
  return;
}
let fileToUpload = <File>files[0];
const formData = new FormData();

formData.append('file', fileToUpload, fileToUpload.name);
this._http.post(this.baseURL + "item/addFile/", formData, { reportProgress: true, observe: 'events' })  
.subscribe(event => {

c#

  [HttpPost, DisableRequestSizeLimit]
    [Route("/item/addFile")]
    public IActionResult Upload()
    {
        try
        {
            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);
                }
                //save to db
                return Ok(new { dbPath });
            }
            else
            {
                return BadRequest();
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex}");
        }
    }

【讨论】:

    猜你喜欢
    • 2017-12-23
    • 2015-10-02
    • 2021-01-29
    • 2021-11-27
    • 1970-01-01
    • 2018-06-04
    • 2020-09-08
    • 2021-07-09
    • 2017-02-23
    相关资源
    最近更新 更多