简体   繁体   English

使用 React JS 和 Laravel 将带有图像文件的 POST 请求发送到数据库时出现内部服务器错误

[英]Getting Internal Server Error when sending POST request with an image file to database using React JS and Laravel

I'm trying to upload an image using React JS and REST API with Laravel as backend.我正在尝试使用 React JS 和 REST API 以 Laravel 作为后端上传图像。

I have a Partner model that has a name and a logo.我有一个有名称和徽标的合作伙伴模型。 I created a form to enter its name and logo.我创建了一个表单来输入其名称和徽标。

When I enter just the name of the partner and submit, I find the new partner added to the database.当我只输入合作伙伴的名称并提交时,我发现新的合作伙伴已添加到数据库中。

But when I try to upload the partner's logo I get this error: POST http://localhost:8000/api/eventpartners 500 (Internal Server Error)但是,当我尝试上传合作伙伴的徽标时,出现此错误:POST http://localhost:8000/api/eventpartners 500(内部服务器错误)

And on my browser, when I go to inspect->Network I find this error: {message: "Array to string conversion", exception: "ErrorException",…}在我的浏览器上,当我去检查->网络时,我发现这个错误:{message: "Array to string conversion", exception: "ErrorException",...}

Here is the AddPartnerForm.js code:这是 AddPartnerForm.js 代码:

import React, { Component } from 'react';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Skeleton from '@material-ui/lab/Skeleton';
import axios, { post } from 'axios';



export default class AddPartnerForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      newPartnerData: {
        partnerlogoimage: '',
        partnername: ''
      },
      partnerlogouploaded: false
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.addPartner = this.addPartner.bind(this)
    this.onUpload = this.onUpload.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }


  onChange(e) {
    this.setState({
      newPartnerData: {
        [e.target.name]: e.target.value
      }
    });
  }

  onUpload(e) {
    let file = e.target.files[0];
    this.setState(prev => ({
      ...prev,
      newPartnerData: {
        ...prev.newPartnerData,
        partnerlogoimage: file,
      },
      partnerlogouploaded: true
    }));
  }

  handleSubmit(e) {
    e.preventDefault()
    this.addPartner();
    console.log(this.state.newPartnerData)
  }

  addPartner() {
    const url = 'http://localhost:8000/api/eventpartners';
    return axios.post(url, this.state.newPartnerData)
      .then((response) => {
        let { partners } = this.state;
        partners.push(response.data);
        this.setState({
          newPartnerData: {
            partnerlogoimage: '',
            partnername: '',
          }
        })
      })
  }


  render() {
    const newPartnerData = this.state.newPartnerData;
    const partnerlogouploaded = this.state.partnerlogouploaded;
    let partnerlogo;
    if (partnerlogouploaded) {
      partnerlogo = <img style={{ width: 200, height: 200 }} src={this.state.partnerlogoimage} />;
    } else {
      partnerlogo = <Skeleton variant="rect" width={200} height={200} />;
    }
    return (
      <form >
        <TextField
          name="partnername"
          autoFocus
          margin="dense"
          id="name"
          label="Partner's name"
          type="text"
          fullWidth
          onChange={this.onChange}
        />
        <input accept="image/*"
          style={{ display: 'none' }}
          id="contained-button-partner-logo"
          name="partnerlogoimage"
          multiple
          type="file"
          diplay="none"
          onChange={this.onUpload} />
        <label htmlFor="contained-button-partner-logo" className="upload-button">
          <Button variant="contained" color="primary" component="span" >
            Upload Partner Logo
        </Button>
        </label>
        <Box width={200} height={200} marginRight={0.5} my={5}>
          {partnerlogo}
        </Box>
        <Button type="submit" onClick={this.handleSubmit} variant="contained" color="primary" component="span" >
          Add
        </Button>
      </form>
    )
  }
}

I'm using Laravel as the backend of this app.我使用 Laravel 作为这个应用程序的后端。

This is the EventPartnerController.php file if it helps:如果有帮助,这是 EventPartnerController.php 文件:

<?php

namespace App\Http\Controllers;

use App\Eventpartner;
use Illuminate\Http\Request;

class EventpartnerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $eventpartners = Eventpartner::all();
        return $eventpartners;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->all();
        $eventpartner = new Eventpartner();
        $eventpartner->event_id = $request->event_id;
        $eventpartner->partnername = $request->partnername;
        $eventpartner->partnerlogoimage = $request->partnerlogoimage;
        $eventpartner -> save();
        return response()->json($eventpartner);
    }

    
}

And this is the routing file api.php :这是路由文件 api.php :

<?php
Use App\Eventpartner;
Use App\Http\Controllers\EventpartnerController;

Route::get('eventpartners', function() {
    return Eventpartner::all();
});
Route::post('eventpartners', 'EventpartnerController@store');

If there's any missing code that I should add to this question please tell me in the comments.如果我应该在这个问题中添加任何缺失的代码,请在评论中告诉我。

You are sending partnerLogoImage in a string type but images should always be send in Blob type to the backend.您以字符串类型发送partnerLogoImage ,但图像应始终以Blob类型发送到后端。 I think your backend is fine but the problem is on Frontend side where you are not using Blob type for image (partnerLogoImage) .我认为您的后端很好,但问题出在前端方面,您没有将Blob类型用于图像 (partnerLogoImage) Please send the image in Blob type in the axios POST request and it will work fine.请在axios POST 请求中发送 Blob 类型的图像,它会正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试将数据用于数据库请求时,为什么Laravel上的AJAX GET / POST会出现“内部服务器错误”? - Why AJAX GET/POST on Laravel does “Internal Server Error” when I try to use data for database request? 发出发布请求时的Laravel 5 Ajax 500(内部服务器错误) - Laravel 5 Ajax 500 (Internal Server Error) when making a post request 通过POST请求发送文件流时出现错误 - Getting error when sending a file stream through a POST request [react] 测试 app.post 创建数据库条目时出现错误代码 HTTP/1.1 500 Internal Server Error - [react]Getting error code HTTP/1.1 500 Internal Server Error when testing app.post to create a database entry 使用Node.js发送发布请求时出现403错误和“n.ajaxTransport.k.cors.a.crossDomain.send” - Getting 403 error and “n.ajaxTransport.k.cors.a.crossDomain.send” when sending a post request using Node.js Laravel AJAX POST请求失败(500内部服务器错误 - Laravel AJAX POST Request failing (500 Internal Server Error 在Angular js中使用定制服务发布请求后出现内部服务器错误 - Internal Server error on post Request Using Made Custom Services in Angular js React JS - CORS 发送 POST 请求时缺少允许 Header - React JS - CORS Missing Allow Header when sending POST request 使用Ajax POST请求将图像和JSON数据发送到服务器? - Sending an image and JSON data to server using Ajax POST request? laravel 和 react 上传文件返回 500 内部服务器错误 - laravel and react upload file return 500 Internal Server Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM