使用 React 和 .Net Core 上传文件

问题描述 投票:0回答:1

我正在尝试上传文件,似乎该文件没有被解析到服务器/后端,因为文件后端的结果为空。我不确定我做错了什么,因为一切似乎都很好。请看我的后端代码以及前端代码: 后端代码

[HttpPost("{projectId}/upload")]
        //[Authorize]
        [ProducesResponseType(204)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> UploadDocument(int projectId, [FromForm] IFormFile file)
        {
            _logger.LogDebug("Inside UploadDocument endpoint");

            // Check if project exists
            var project = await _context.Projects.FirstOrDefaultAsync(p => p.ProjectId == projectId);

            if (project == null)
            {
                _logger.LogError($"An item in Project could not be found with ID: {projectId}");
                throw new NotFoundException($"An item in Project could not be found with ID: {projectId}");
            }

            if (file != null && file.Length > 0)
            {
                // Get project folder path
                //var repositoryPath = @"G:\Shares\GT Repository";
                var repositoryPath = @"D:\Uploads";
                var projectFolderPath = Path.Combine(repositoryPath, project.ProjectNumber);
                //var projectFolderPath = Path.Combine(repositoryPath);

                // Creates sub folders >>> future implementation

                if (!Directory.Exists(projectFolderPath))
                {
                    Directory.CreateDirectory(projectFolderPath);

                    // Create subfolders for document types
                    var documentFolders = new List<string>
                    {
                        "Quote",
                        "Customer PO",
                        "Invoice",
                        "Job Card",
                        "Delivery Note",
                        "Costing Sheet"
                    };

                    foreach (var folderName in documentFolders)
                    {
                        var documentFolderPath = Path.Combine(projectFolderPath, folderName);

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

                // Generate a unique file name
                var uniqueFileName = project.ProjectNumber + "_" + Guid.NewGuid().ToString() + "_" + file.FileName;
                //var uniqueFileName = Guid.NewGuid().ToString() + "_" + file.FileName;

                var filePath = Path.Combine(projectFolderPath, uniqueFileName);

                using(var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                return NoContent();
            }

            _logger.LogError("No file provided for upload.");
            throw new BadRequestException("No file provided for upload.");
        }

前端代码:

const [file, setFile] = useState({
    quote: null,
    po: null,
    invoice: null,
    jobCard: null,
    deliveryNote: null,
    costingSheet: null
  })

const handleFileChange = (e) => {
    const { name, files } = e.target;

    setFile({
      ...file,
      [name]: files[0],
    });

  };


if(file){
      const formData = new FormData();

      for (const name in file) {
        const uploadedFile = file;
        if (uploadedFile) {
          formData.append(name, uploadedFile);

          console.log(uploadedFile)

          try{

            const result = await axios.post(`https://localhost:7281/api/Project/${values.projectId}/upload`, formData, {
              headers: {
                "Content-Type": "multipart/form-data",
                Accept: "application/json",
              },
            })

            console.log(result);
          }catch(error){
            console.log("Error occurred: ",error);
          }
        }
      }
    }

<input
                className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-2 mb-2 ${fileStyles.customFileInput}`}
                id="quote"
                name="quote"
                type="file"
                accept="application/pdf"
                title="Attach Quote"
                onChange={handleFileChange}
              />

<input
                className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-1 mb-2 ${fileStyles.customFileInput}`}
                id="po"
                name="po"
                type="file"
                accept="application/pdf"
                title="Attach PO"
                onChange={handleFileChange}
              />

<div className="flex justify-evenly mt-3">
            <div>
                <label className="ml-2" htmlFor="jobCard">Attach Job Card</label>
                <input
                  id="jobCard"
                  name="jobCard"
                  className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-2 ${fileStyles.customFileInput}`}
                  type="file"
                  accept="application/pdf"
                  title="Attach Job Card"
                  onChange={handleFileChange}
                />
            </div>
                <div>
                  <label className="ml-2" htmlFor="deliveryNote">Attach Delivery Note</label>
                  <input
                    id="deliveryNote"
                    name="deliveryNote"
                    className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-2 ${fileStyles.customFileInput}`}
                    type="file"
                    accept="application/pdf"
                    title="Attach Delivery Note"
                    onChange={handleFileChange}
                  />
                </div>
                <div>
                  <label className="ml-2" htmlFor="costingSheet">Attach Costing Sheet</label>
                  <input
                    id="costingSheet"
                    name="costingSheet"
                    className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-2 ${fileStyles.customFileInput}`}
                    type="file"
                    accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    title="Attach Costing Sheet"
                    onChange={handleFileChange}
                  />
                </div>
            </div>

添加控制台日志显示文件及其数据,通过有效负载检查网络选项卡也显示文件值,但文件不会解析到服务器,formData返回一个空对象,导致文件在后端为空

reactjs asp.net-core asp.net-core-webapi form-data
1个回答
0
投票

您可以尝试这些在我的测试中有效的更改。
1.在webapi后端添加CORS策略。

builder.Services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
    builder
        .AllowAnyOrigin()
        .AllowAnyHeader()
    .AllowAnyMethod();
}));
app.UseCors("CorsPolicy");

2.修改

handleFileChange

    const handleFileChange= (e) => {
    //in case you wan to print the file selected
    //console.log(e.target.files[0]);
    setFile(e.target.files[0]);
  };

工作样本

import React, { useState } from "react";
import axios from "axios";

export const FileUpload = () => {
  const [fileSelected, setFileSelected] = useState();

    const handleFileChange= (e) => {
    //in case you wan to print the file selected
    //console.log(e.target.files[0]);
    setFileSelected(e.target.files[0]);
  };


  const importFile= async (e) => {
    const formData = new FormData();

    for (const name in fileSelected) {
      const uploadedFile = fileSelected;
      if (uploadedFile) {

    formData.append("file", uploadedFile);
    try {
      const res = await axios.post("https://localhost:7161/1/importfile", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          Accept: "application/json",
        },
      });
    } catch (ex) {
      console.log(ex);
    }
  };}}
    

  return  (
    <>
    <input
                // className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-2 mb-2 ${fileStyles.customFileInput}`}
                id="quote"
                name="quote"
                type="file"
                accept="application/pdf"
                title="Attach Quote"
                onChange={handleFileChange}
              />

<input
                // className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-1 mb-2 ${fileStyles.customFileInput}`}
                id="po"
                name="po"
                type="file"
                accept="application/pdf"
                title="Attach PO"
                onChange={handleFileChange}
              />

<div className="flex justify-evenly mt-3">
            <div>
                <label className="ml-2" htmlFor="jobCard">Attach Job Card</label>
                <input
                  id="jobCard"
                  name="jobCard"
                  //className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-2 ${fileStyles.customFileInput}`}
                  type="file"
                  accept="application/pdf"
                  title="Attach Job Card"
                  onChange={handleFileChange}
                />
            </div>
                <div>
                  <label className="ml-2" htmlFor="deliveryNote">Attach Delivery Note</label>
                  <input
                    id="deliveryNote"
                    name="deliveryNote"
                    //className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-2 ${fileStyles.customFileInput}`}
                    type="file"
                    accept="application/pdf"
                    title="Attach Delivery Note"
                    onChange={handleFileChange}
                  />
                </div>
                <div>
                  <label className="ml-2" htmlFor="costingSheet">Attach Costing Sheet</label>
                  <input
                    id="costingSheet"
                    name="costingSheet"
                    //className={`w-full md:w-full px-2 md:mb-0 block uppercase tracking-wide text-gray-700 text-xs font-bold mt-2 ${fileStyles.customFileInput}`}
                    type="file"
                    accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    title="Attach Costing Sheet"
                    onChange={handleFileChange}
                  />
                </div>
            </div>

            <input type="button" value="upload" onClick={importFile} />

    </>
  )
    
};
© www.soinside.com 2019 - 2024. All rights reserved.