【问题标题】:Upload large file with axios react and .net core使用 axios react 和 .net core 上传大文件
【发布时间】:2023-03-04 12:25:01
【问题描述】:

我需要在 iis 服务器上上传一个大文件(100MB)。 为什么以下代码适用于较小的文件(13MB)。 我在上传大文件时遇到的错误是:

访问 XMLHttpRequest 在 'https://localhost:44331/api/Files/uploadFile?hidden=false' 来自 来源 'http://localhost:3000' 已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

感谢您的帮助。

这是带有 axios 和 react 的前端 sn-p:

public upload = async (filesForUploading: File[], progressLogger: (progress: IProgress) => void, 
hidden?: boolean) => {
    const createPostRequest = (item: File) => {
        const formData = new FormData();
        formData.append("file", item, item.name);
        const request = this.agent.post<IFile>(`${this.url}/uploadFile?hidden=${hidden || false}`, 
       formData, {
            headers: {
                "Content-Type": "multipart/form-data",
                "Access-Control-Allow-Origin": "*",
            },
            onUploadProgress: (progressEvent: ProgressEvent) => {
                
                progressLogger({ file: item, uploaded: progressEvent.loaded / progressEvent.total, 
 id: URL.createObjectURL(item) });
                
                
            },
        });
        return request;
    };
    const requests = filesForUploading.map(createPostRequest);

    const getData = (all: Array<AxiosResponse<IFile>>) => all.map(res => res.data);
    const response = await Promise.all(requests);
    return getData(response);
};

这是.net core的后端方法:

       [HttpPost("uploadFile", Name = nameof(UploadFile))]
       [ProducesResponseType(200)]
       [ProducesResponseType(400)]
       [ProducesResponseType(404)]
       [DisableRequestSizeLimit]
       public async Task<ActionResult<FileViewModel>> UploadFile(IFormFile file, bool hidden = false)
       {
        FileViewModel uploadedFile = null;
        User loggedUser = await _userService.GetLoggedUser(User);
        try
        {
            uploadedFile = await _fileService.UploadFile(file, loggedUser, hidden);

        }
        catch (Exception error)
        {
            return NotFound(error);
        }

        return Ok(uploadedFile);
    }

【问题讨论】:

  • 您收到的错误消息以及您捐赠的原因是没有意义的。您确定错误源于上传的大文件吗?那么,上传小文件时,完全相同的代码是否成功?
  • 是的。是相同的代码。
  • 如果你需要上传任何大小的文件,你可以使用这个答案:stackoverflow.com/a/69990677/10203847

标签: c# reactjs .net-core file-upload axios


【解决方案1】:

据我所知,IIS 中的默认文件大小限制为 30 MB。 为了增加它,您应该在 web.config 文件的 requestLimits 部分中指定限制。您可以在official docs 中找到描述和示例: 此外,您可能需要在 Startup.cs 中配置 IISServerOptionsKestrelServerOptions。您可以在this StackOverflow question 中找到示例。

无论如何,错误消息表明 CORS 策略存在问题,而不是文件大小。我可能会认为问题不仅是由文件大小限制引起的,而且是由其他配置错误引起的。

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 2021-09-12
    • 2019-08-06
    相关资源
    最近更新 更多