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)表示FormData0项(见图像连接),也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.cs

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);
  }

此外,如果想要发送文件服务器使用后的请求,也无法转换成字符串的文件,你想发送。 你是什么发现在式有效载荷看起来像这样 "files": {}. 你需要serialize它在一个不同的方式。 这意味着需要改变你的方式发送这个文件。 检查的回答这个问题: 我怎么上传文件的JS取API?

序列化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

因此,开始从拉扎尔*尼科利奇的回答上述停止试图手机中。转换成字符串!.. 后绊脚石到一些阻滞剂在这里和那里我终于能够发送一个文件成功的API!!

这里有一些重要的步骤以注意:

在后台-我改变了控制的方法:

  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. 注意到电子邮件的目的是收到的所有属性设定为无直到我删除了内容类型的标题和随后的浏览器将增加multipart/form-data头本身。。我得到这种帮助从@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ý
..................................................................................................................