reactjs redux axios prob with img upload (symf in back)

我封了2天的图片上传。我有一个表格,里面有日期、字符串、布尔和图像等内容。这是为了在我的网站上创建一个公告。

我们实际上使用了 Reactjs, Redux, Axios, Datepicker。

这是我的代码。(对不起,如果它是废话,我是初学代码…)

Component (用于img) :

<form id="myform" onSubmit={onCreateAnnouncementSubmit} method="post" >
{...}

<div className="createAnnouncement__input drop desktop input">
          <input 
            type="file" 
            className="input" 
            accept=".png, .jpg, .jpeg" 
            name={picture}
            onChange={fileChangedHandler}  
          />
</div>
{...}
<div className="createAnnouncement__flex">
        <button type="submit" className="createAnnouncement__button button">Créer</button>
</div>

Container :

import CreateAnnouncement from '../components/CreateAnnouncement';
import { inputCreateAnnouncement,  postCreateAnnouncement, passId} from '../Redux/actions'
import {connect} from 'react-redux';

const mapStateToProps = ({data}) => {
  return({
   {...}
    picture: data.create.picture,    
  })
};

const mapDispatchToProps = (dispatch, {match}) => ({

  onCreateAnnouncementSubmit: (e) => {e.preventDefault(); dispatch(passId(postCreateAnnouncement))},

  fileChangedHandler = (event) => dispatch(inputCreateAnnouncement({ [e.target.name]: {
    selectedFile: event.target.files[0]
  }})),

})
;

const createAnnouncement = connect(mapStateToProps, mapDispatchToProps)(CreateAnnouncement);

export default createAnnouncement;

这里有一些动作。

export const INPUT_CREATE_ANNOUNCEMENT= 'INPUT_CREATE_ANNOUNCEMENT';

export const inputCreateAnnouncement = (payload) => ({
  type: INPUT_CREATE_ANNOUNCEMENT,
  payload
})


export const postCreateAnnouncement = () => (dispatch, getState) => {
  const fd = new FormData();
  fd.append('image', selectedFile)
  axios({
    headers: {      
      ContentType: 'multipart/form-data',
      Authorization: `bearer ${token()}`,
    },
    method: 'post',
    url: `***********/api/announcements/`, 
    data: 
    {             
      user_id: getState().login.userId,
      category: "default",      
      ...getState().data.create          
    }
  })
  .then((res) => console.log(res))
  .catch((err) => console.log(err))
};

export const passId = (func) => (dispatch, getState) => {
  dispatch(func(getState().login.userId))
}

还有数据:

const initialState = {
  create: {
 {...}
    picture: null,     
  },

{...}

case INPUT_CREATE_ANNOUNCEMENT:
      return {
        ...state,
        create:{...state.announcements[0], ...action.payload}
      }

在我的symfony中。

/**
     * @Route("/", name="add", methods={"POST"})
     */
    public function add(Request $request, GetErrorsFromForm $getErrorsFromForm)
    {
        $announcement = new Announcement();
        // On décode les données envoyées
        $donnees = json_decode($request->getContent(), true);
        /** On verifie si la propriété est envoyé dans le json si oui on hydrate l'objet 
         * sinon on passe à la suite */
        $form = $this->createForm(AnnouncementType::class, $announcement);
        $form->submit($donnees);
        $donnees = json_decode($request->getContent(), true);
        $form = $this->createForm(AnnouncementType::class, $announcement);
        //dd($announcement);
        $form->submit($donnees, false);
        if ($form->isValid()) {
            $announcement->setCreatedAt(new \DateTime);
            if ($form['picture']->isSubmitted() && $form['picture']->isValid()){
            /** @var UploadImage 
             * $uploadedFile */

            $uploadedFile = $form['picture']->getData();
            $destination = $this->getParameter('kernel.project_dir').'/public/uploads/AnnouncementPicture';
            $originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
            $newFilename = $originalFilename.'-'.uniqid().'.'.$uploadedFile->guessExtension();
            $uploadedFile->move(
                $destination,
                $newFilename
            );}
            $em = $this->getDoctrine()->getManager();
            $em->persist($announcement);
            $em->flush();
            return new JsonResponse('ok', 201);
        } else {
            $errors = $getErrorsFromForm->getErrors($form);
            $data = [
                'type' => 'validation_error',
                'title' => 'There was a validation error',
                'errors' => $errors,
            ];
            return new JsonResponse($data, 400);
        }
    }

先谢谢你,对不起,我的英语不好… …

解决方案:

你可以用 axios 发送你的表单信息,使用的是 表格数据 像这样。

  const firstName = 'my_first_name';
  const lastName = 'my_last_name';
  const date = '2020-04-10';// date in format that your backend supports
  const fd = new FormData();
  fd.append('name', firstName)
  fd.append('last_name', lastName);
  fd.append('file', selectedFile);
  fd.append('date', date);
  axios({
    headers: {      
      ContentType: 'multipart/form-data',
      Authorization: `bearer ${token()}`,
    },
    method: 'post',
    url: `***********/api/announcements/`, 
    data: fd

  })
  .then((res) => console.log(res))
  .catch((err) => console.log(err))

你可以阅读更多。axios post请求发送表单数据 axios – 发送表格数据和非表格数据

给TA打赏
共{{data.count}}人
人已打赏
未分类

为什么我们需要在 react 中绑定一个事件处理程序?

2022-9-8 1:28:37

未分类

如何能够确定我的麦克风在微软团队中时是否能够工作?[关闭]

2022-9-8 1:28:39

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索