【问题标题】:Getting System.FormatException: Input string was not in a correct format. while trying to upload a file from angular获取 System.FormatException:输入字符串的格式不正确。在尝试从角度上传文件时
【发布时间】:2023-02-26 06:11:04
【问题描述】:

System.FormatException:尝试将文件从我的角度应用程序上传到 asp.net 6 后端 api 时,输入字符串的格式不正确。我的客户端代码如下

 onFileSelected(event: any) {

    this.selectedFile = event.target.files[0];
    const formData = new FormData();
    formData.append('file', this.selectedFile, this.selectedFile.name);    
    debugger;
    const file: File = event.target.files[0];
  
    // const formData = new FormData();
    // formData.append('file', file);
  
    this.http.post(this.BaseUrl + '/api/FileUpload/upload', formData).subscribe(response => {
      console.log('File uploaded successfully');
    });
  }

和服务器端代码为

    [HttpPost("upload")]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        // Retrieve the connection string from configuration
        var connectionString = _storageConnectionString;

        // Create a BlobServiceClient object
        var blobServiceClient = new BlobServiceClient(connectionString);

        // Get a reference to the container where you want to upload the file
        var containerName = "mycontainer";
        var containerClient = blobServiceClient.GetBlobContainerClient(containerName);

        // Create a unique name for the blob
        var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);

        // Upload the file to Azure Storage
        var blobClient = containerClient.GetBlobClient(fileName);
        await blobClient.UploadAsync(file.OpenReadStream(), true);

        // Return a response to the client
        return Ok();
    }

这非常令人沮丧,因为我无法为该问题找到任何解决方案。任何人都可以在这里帮助我。

结果代码永远不会到达后端,因为我从来没有在后端遇到调试器,而在尝试从 swagger 测试方法时,它工作正常。

【问题讨论】:

    标签: angular asp.net-core file-upload angular-material azure-blob-storage


    【解决方案1】:

    我从来没有设法让 IFormFile 工作,我想这应该是所使用的类的过去。

    我的第一个 Google result 看起来像我过去使用的代码。这已被验证有效。

    您需要更改的部分是您在 dotnet core 中读取文件的方式。

    [HttpPost, DisableRequestSizeLimit]
    public async Task<IActionResult> Upload()
    {
        try
        {
            var formCollection = await Request.ReadFormAsync();
       
            var file = formCollection.Files.First();
    
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2011-11-23
      • 2022-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多