FormData ว่างเปล่าในตอนที่พ่อแม่ผ่านจากเด็กส่วนประกอบ

0

คำถาม

เชิดแพลตตินั่มทั้งหมดไปใช่เตือน! :ฉันการตั้งค่า FormData ในเด็กส่วนประกอบและส่งมันให้พ่อแม่ส่วนประกอบการใช้ formReducer และข่าวด่วน,แต่พ่อแม่ formData.รายการ()จะเป็นเสมอเปล่า!

ChildComponent.js

function ChildComponent({signed, fileAttached}){
    const { dispatch } = useContext(ContactFormContext);

     const changeHandler = (event) => {

const formData = new FormData();

formData.append('File', event.target.files[0]);


dispatch({ type: "FILE_ATTACHED", payload: formData })
};

return (
<>
            <div>
        <input type="file" name="file" onChange={changeHandler} />
    </div>
</>);
}

ParentComponent.js

function useFormProgress(fileAttached) {
     
     
    function goForward() {
        const currentStep = 1;

        let appvariables = [
                {
                  "key": "PUID",
                  "value": "a2sd"
                },
                {
                  "key": "ApplicationNames",
                  "value": "Trello, abc"
                }
              ];
        switch(currentStep) {
          case 0:
            break;
          case 1:
            console.log(fileAttached);
          if(fileAttached != null)
              sendEmail("Resignation Letter", appvariables, fileAttached);
          break;
        }
    }
    return [goForward];
}

function sendEmail(templateName, variables, attachment){
  console.log("sending email...");
    const requestBody = {
                    "templateName": templateName,
                    "recipients": [    
                    "[email protected]"
                    ],
                    "variables":  variables,
                    "files": attachment
                };

fetch('https://localhost:5001/api/Email',{
  method:'Post',
  body: JSON.stringify(requestBody),
  headers:{'Content-Type': 'application/json'},
 });

}

const initialState = {
      signed: "",
      fileAttached: null
};

function formReducer(state, action) {
   switch (action.type) {
    case "SIGNED":
      return { ...state, signed: action.payload };
    case "FILE_ATTACHED":
      return {...state, fileAttached: action.payload};
    default:
      throw new Error();
  }
}


function ParentComponent() {

   const [state, dispatch] = useReducer(formReducer, initialState);
     const { signed, fileAttached } = state;

     const steps = [<ChildComponent {...{signed, fileAttached}}/>];

   const [goForward] = useFormProgress(fileAttached);


    return (
        <ContactFormContext.Provider value={{ dispatch }}>
          <div>{steps[0]}
        <div><button onClick={e => {
           e.preventDefault();
              goForward();
        }}
             
        >  Parent Button
        </button>
        </div>
    </div>
        </ContactFormContext.Provider>
       );
}

ContactFormContext.js

const ContactFormContext = React.createContext();

ในที่เปลี่ยนคำให้การด้านบน(ParentComponent),คอนโซล.ปูมบันทึก(FileAttached)แสดง FormData กับ 0 รายการ(ดูมอดูลของภาพติด)เหมือนกันที่รูปแบบ api การร้องขอไม่ประสบความสำเร็จ!

enter image description here

คุณสามารถลองมันออกไป https://jscomplete.com/playground

  1. เพิ่มไอคอนถาดระบบขอบด้านบน

  2. เพิ่มเด็กส่วนประกอบรหัส

  3. เพิ่ม parentcomponent รหัส

  4. เพิ่มคลังตามเส้น

      ReactDOM.render(<ParentComponent/>, mountNode);
    

MyAPI วิธีการ

[HttpPost]
    public JsonResult Get(EmailRequest email)
    {
         //the request never comes here
     }

EmailRequest.à™àà§à•à£àà™

public class EmailRequest
{
    public string TemplateName { get; set; }
    public string[] Recipients { get; set; }
    public List<Variables> Variables { get; set; }
    public FormFileCollection files { get; set; }
}
asp.net-web-api c# file-upload form-data
2021-11-23 09:18:20
3

คำตอบที่ดีที่สุด

1

เพื่อให้ได้ค่าจากรายการวิธีการของ FormData โดยการใช้คอนโซล.ปูมบันทึกคุณควรจะทำมันเหมือนนี้:

  for (var [key, value] of attachment.entries()) {
    console.log("log from for loop", key, value);
  }

แล้วก็ถ้าคุณต้องการจะส่งแฟ้มไปยังเซิร์ฟเวอร์โดยใช้โพสการร้องของคุณไม่สามารถ stringify แฟ้มที่คุณต้องการจะส่ง. สิ่งที่คุณกำลังส่งตอนนี้ในของคุณ language ยมหัวรบของนายให้ดูเหมือนนี้ "files": {}. คุณต้อง serialize มันในมุมมองที่ต่างออกเห็น. นี่หมายความว่าคุณต้องเปลี่ยนแปลงที่คุณกำลังส่งแฟ้มนี้ได้ ตรวจดูคำตอบของคำถาม: ยังไงฉันอัพโหลดแฟ้มกับ JS อข้อมูลรูปแบบ api?

สำหรับ serializing FormData คุณสามารถตรวจสอบได้นี่โพสต์: https://gomakethings.com/serializing-form-data-with-the-vanilla-js-formdata-object/

2021-11-23 10:24:12
0

ฉันเพิ่มของคุณรหัสใน codesandbox และทุกอย่างดูเหมือนจะไม่เป็นไรหรอก

Codesandbox สาธิต

enter image description here

2021-11-23 10:15:22
0

งั้นเริ่มจาก Lazar Nikolic เป็นคำตอบอยู่เหนือหยุดพยายาม language.stringify!.. หลังจากเดินไปสะดุดเข้ากับบาง blockers อยู่ที่นี่และที่นั่นในที่สุดฉันก็สามารถส่งแฟ้มเรียบร้อยแล้ไปที่รูปแบบ api!!

ที่นี่เป็นบางอย่างสำคัญขั้นตอนที่ข้อควรทราบ:

ในโปรแกรมเบื้องหลัง-ฉันเปลี่ย controller วิธีการ:

  1. เพิ่ม[FromForm]ป้ายกำกับ

    [HttpPost]
     public JsonResult Get([FromForm] EmailRequest email)
    

มัลัง ช่วยฉัน

อยู่ในหน้าสุดด้านข้าง

  1. เปลี่ยนไป ChildComponent.js ตาม

    function ChildComponent({signed, fileAttached}){
    const { dispatch } = useContext(ContactFormContext);
    
    const changeHandler = (event) => {
    
    dispatch({ type: "FILE_ATTACHED", payload: event.target.files[0] })
    };
    
    return (
    <>
         <div>
     <input type="file" name="file" onChange={changeHandler} />
    </div>
    </>);
    }
    
  2. เปลี่ยน sendEmail ฟังก์ชันใน ParentComponent.js ตาม

    function sendEmail(templateName, variables, attachment){
      console.log("sending email...");
    
      const formData = new FormData();
    
     formData.append('files', attachment);
     formData.append('templateName', templateName);
     formData.append('recipients', [    
      "[email protected]"
     ]);
     formData.append('variables', variables);
    
    
    fetch('https://localhost:5001/api/Email',{
    method:'Post',
    body: formData,
    //headers:{'Content-Type': 'application/json'},
    });
    
    }
    
  3. สังเกตเห็นอีเมลวัตถุที่ได้รับเพราะผลจากทั้งหมดคุณสมบัติของตั้งเป็นโพรโทคอล aimcomment จนกว่าฉันเอาเนื้อหาประเภทส่วนหัวแล้วก็เบราว์เซอร์จะทำการเพิ่ม multipart/รูปแบบ-ข้อมูลส่วนหัวตัวเอง..ฉันมีความช่วยเหลือจาก@madhu131313 เป็นความคิดเห็น ที่นี่

  4. เราไม่สามารถส่งออบเจ็กต์อาเรย์โดยตรงอยู่ใต้รูปแบบ-ข้อมูลดังนั้นตัวแปรอาเรย์นเป็นที่ว่างเปล่า..ฉันทำต่อไปนี้

    for(let i = 0; i < variables.length; i++){
     formData.append(`variables[` + i + `].key`, variables[i].key);
     formData.append(`variables[` + i + `].value`, variables[i].value);
    }
    

แทนที่จะเป็น

   formData.append('variables', variables);

และเปลี่ยนผู้รับตาม:

   let recipients = [    
  "[email protected]",
  "[email protected]",
  "[email protected]"
  ];

   for(let i = 0; i < recipients.length; i++){
    formData.append(`recipients[` + i + `]`, recipients[i]);
  }
2021-11-23 10:22:16

ในภาษาอื่นๆ

หน้านี้อยู่ในภาษาอื่นๆ

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................

ดังอยู่ในนี้หมวดหมู่

ดังคำถามอยู่ในนี้หมวดหมู่