next.js 如何在Web Core API dotnet 5中同时上传文件和保存数据

gk7wooem  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(107)

我尝试在coreweb API中同时上传文件和保存数据,使用nextjs作为前端和asp dotnet core作为后端API,我无法将数据发送到core web API?我应该如何发送对象数据,下面是JSON格式的数据。

{
  "sNo": "string",
  "applicationName": "string",
  "status": "string",
  "applicationDescription": "string",
  "entryBy": "string",
  "entryDate": "string",
  "action": "string",
  "softwareBillingDetails": [
    {
      "sNo": "string",
      "version": "string",
      "certificationNo": "string",
      "frontEnd": "string",
      "backEnd": "string",
      "certificatedDate": "string",
      "action": "string"
    }
  ],
  "softwareBillingDocument": [
    {
      "sNo": "string",
      "documentType": "string",
      "includedYN": "string",
      "action": "string"
    }
  ],
  "softwareVendors": [
    {
      "sNo": "string",
      "pan": "string",
      "vendorName": "string",
      "vendorType": "string",
      "contactNo": "string",
      "developerForDistibuters": "string",
      "developerCountry": "string",
      "action": "string"
    }
  ],
  "softwareBillingEquipmentInfo": [
    {
      "sNo": "string",
      "version": "string",
      "equipSno": "string",
      "equipmentName": "string",
      "brandName": "string",
      "modelNo": "string",
      "countryName": "string",
      "manufacturingDate": "string",
      "builtInSoftware": "string",
      "frontEnd": "string",
      "backEnd": "string"
    }
  ],
  "requestedDate": "string",
  "approvedDate": "string",
  "applicantName": "string",
  "designation": "string",
  "applicantEmail": "string",
  "applicantPhone": "string",
  "applicantMobile": "string",
  "website": "string",
  "remarks": "string",
  "softwareBillingDocumentFile": [
    {
      "submissionNo": "string",
      "seqNo": 0,
      "documentType": "string",
      "fileName": "string",
      "pdfFile": "string"
    }
  ],
  "applicationDisName": "string"
}

我想在softwareBillingDocumentFile in pdfFile上传文件,因为我有模型,如下面上传的PDF如下

public class SoftwareBillingDocumentFile
        {
            public string SubmissionNo { get; set; }
            public object Document { get; set; }
            public int SeqNo { get; set; }
            public string DocumentType { get; set; }
            public string FileName { get; set; }
            public IFormFile? PdfFile { get; set; }
        }

我正在以这种方式上传数据,但我无法上传

functionName([FromForm] List<SoftwareBillingDocumentFile> softwareBillingDocumentFile, string SubmissionNo`)
     {
    
                    if (softwareBillingDocumentFile[0].PdfFile != null)
                    {
                        IFormFile formFile = softwareBillingDocumentFile[0].PdfFile;
                        string extension = System.IO.Path.GetExtension(formFile.FileName);
                        if (extension == ".pdf")
                        {
                            Int64 contentLength = formFile.Length / 1024;
                            if(contentLength > 51200) //allow oly upto 5mb
                            {
                                string errorfile = "file size greater than 5mb is not allowed";
                                returnMessage = ReturnHelper.ReturnMessage("err", (int)System.Net.HttpStatusCode.SeeOther, data: errorfile);
                            }
                            else
                            {
                                string fileName = formFile.FileName.Replace(" ", "");
                                 GuidfileName = this.RandomString(10) + "_" + fileName;
                                string filepath = Path.Combine(Directory.GetCurrentDirectory(), "fileupload", GuidfileName);
                                using (Stream stream = new FileStream(filepath, FileMode.Create))
                                {
                                    softwareBillingDocumentFile[0].PdfFile.CopyTo(stream);
                                    
                                }
                            }
    
                        }
                        else
                        {
                            string errorfile = "file type not supported";
                            returnMessage = ReturnHelper.ReturnMessage("err", (int)System.Net.HttpStatusCode.SeeOther, data: errorfile);
    
                        }
    
                    }
    }

我如何假设发送数据,我已经尝试通过创建formData对象,并分配formData对象到pdfFile,但它返回空对象,无法上传fike
验证码:

const fileUploadHandler = (e) => {
    const formData = new FormData();
    const file = e.target.files[0];
    formData.append("document", e.target.files[0].name);
    setUserData((prev) => ({...prev,
        SoftwareBillingDocumentFile: [{
            FileName: file.name,
            PdfFile: formData,
            DocumentType: file.type,
            SubmissionNo: "800030444804",
            document: "",
            seqNo: 0,
        },],
    }));
};
brqmpdu1

brqmpdu11#

你还没有分享你实际上是如何执行上传的。但是,当您调用API并在请求中包含正确的标头时,需要向FormData传递单个files对象。
下面是一个简化的版本,展示了一个应该适用于单个文件的示例:

let file = e.target.files[0];

formData.append("PdfFile", file);
formData.append("FileName", file.name);
formData.append("SubmissionNo", "800030444804");
formData.append("document", "");
formData.append("seqNo", 0);

axios.post(UPLOAD_ENDPOINT, formData, {
    headers: {
        "content-type": "multipart/form-data"
    }
}).then(data => {
    console.log(data.data);
}).error(error => {
    console.log(error);
});

显然,您希望上传多个文件,这很好,但目前您没有将单个文件分配给对象,而是将所有提交的FormData附加到属性PdfFile,这是不正确的。
上面的代码获取了e.target.files[0](第一个文件)的值,并将其发布在FormData内的PdfFile属性下,这是正确的。
考虑到这一点,您可以修改现有代码,将file FormData对象保存到您将存储的对象中,以便处理并发送到API:

const fileUploadHandler = (e) => {
    const formData = new FormData();
    const file = e.target.files[0];
    // formData.append("document", e.target.files[0].name); not required
    setUserData((prev) => ({...prev,
        SoftwareBillingDocumentFile: [{
            FileName: file.name,
            PdfFile: file, // Assign the file to the object
            DocumentType: file.type,
            SubmissionNo: "800030444804",
            document: "",
            seqNo: 0,
        },],
    }));
};

你不能在一个请求中将JSON和FormData混合在一起,然后直接将其发送到服务器,除非你要显式地将其转换为application/mixed数据并以不同的方式格式化它(IE。而不仅仅是包含FormData的JSON)。
所以为了简化事情,只需要使用纯粹的FormData并将JSON状态转换为控制器可以理解的数据,就像这样:

// Get the files from the state
let documentFiles = myObject.SoftwareBillingDocumentFile;
let formData = new FormData();

for (let i = 0; i< documentFiles.length; i++) {

    let documentFile = documentFiles[i];

    // Build the form data for the submission
    for (var key in documentFile) {
        formData.append(key + '[' + i + ']', documentFile[key]);
    }
}

axios.post(UPLOAD_ENDPOINT, formData, {
    headers: {
        "content-type": "multipart/form-data"
    }
}).then(data => {
    console.log(data.data);
}).error(error => {
    console.log(error);
});

这段代码将所有数据作为FormData发送,这是您的控制器所期望的。

相关问题