javascript 如何使用fetch发布图片?

kmpatx3s  于 2023-10-14  发布在  Java
关注(0)|答案(4)|浏览(99)

我刚刚学习React,我创建了一个画廊应用程序,但我有问题,张贴图片到API。问题是,当我点击按钮ADD时,什么也没有发生,只是在console.log中,我得到了一个error 500

这里是我的组件与后请求:

class AddPhoto extends Component {
constructor(props) {
    super(props);
    this.state = {
        modal: false,
        images: [],
        isLoading: false,
        error: null,
    };

    this.toggle = this.toggle.bind(this);
    this.handleClick = this.handleClick.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

toggle() {
    this.setState({
        modal: !this.state.modal
    });
}

handleClick(event) {
    event.preventDefault();
    this.setState({
        modal: !this.state.modal
    });
}

handleSubmit(event){
    event.preventDefault();

    this.setState({ isLoading: true });
    let path = this.props.path;

    fetch(`http://.../gallery/${path}`, {
        method: 'POST',
        headers: {'Content-Type':'multipart/form-data'},
        body: new FormData(document.getElementById('addPhoto'))
    })
        .then((response) => response.json())
        .then((data)=>{
            this.setState({images: data.images, isLoading: false});
            this.props.updateImages(data.images);
        })
        .catch(error => this.setState({ error, isLoading: false}));
}

render() {
    return (
        <Card className="add">
            <div className="link" onClick={this.toggle}>
                <CardBody>
                    <CardTitle>Add picture</CardTitle>
                </CardBody>
            </div>
            <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
                <div className="modal-header">
                    ...
                </div>
                <ModalBody>
                    <form className="addPhotoForm" id="addPhoto" onSubmit={this.handleSubmit}>
                        <input type="file" required />
                        <Button color="success" type="Submit">Add</Button>
                    </form>
                </ModalBody>
            </Modal>
        </Card>
    );
}
}
  • 你有任何想法我做错了什么,为什么不工作,为什么我得到错误500?*

谢谢你帮我

bjp0bcyl

bjp0bcyl1#

根据这个https://muffinman.io/uploading-files-using-fetch-multipart-form-data它的工作方式不同,至少对我来说它的工作以及。

const fileInput = document.querySelector('#your-file-input') ;
const formData = new FormData();

formData.append('file', fileInput.files[0]);

    const options = {
      method: 'POST',
      body: formData,
      // If you add this, upload won't work
      // headers: {
      //   'Content-Type': 'multipart/form-data',
      // }
    };
    
    fetch('your-upload-url', options);

你应该删除'Content-Type': 'multipart/form-data',它开始工作。

raogr8fs

raogr8fs2#

这是我上传组件的一部分。看看我是怎么做的,你可以修改它,上传按钮,如果你需要的话。

addFile(event) {
    const formData = new FormData();
    formData.append("file", event.target.files[0]);
    formData.append('name', 'some value user types');
    formData.append('description', 'some value user types');
    console.log(event.target.files[0]);

    fetch(`http://.../gallery/${path}`, {
        method: 'POST',
        headers: {'Content-Type': 'multipart/form-data'},
        body: {event.target.files[0]}
    })
    .then((response) => response.json())
    .then((data) => {
        this.setState({images: data.images, isLoading: false});
        this.props.updateImages(data.images);
    })
    .catch(error => this.setState({error, isLoading: false}));
}

render() {
    return (
        <div>
            <form encType="multipart/form-data" action="">
                <input id="id-for-upload-file" onChange={this.addFile.bind(this)} type="file"/>
            </form>
        </div>)
}
yqyhoc1h

yqyhoc1h3#

这对我来说很好,试试看:

var myHeaders = new Headers();
myHeaders.append("Accept", "application/json");
myHeaders.append("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJh");

var formdata = new FormData();    
formdata.append("image", fileInput.files[0], "Your_iamge_URL");

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: formdata,
  redirect: 'follow'
};

fetch("YOUR_API_ToCall", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
cbwuti44

cbwuti444#

如果您需要发送一个属性多于图像的请求,请用途:

document.getElementById('inputPhoto').addEventListener('change', (e) => {  
  const data = new FormData();
  const image = e.target.files[0];
  data.append('id', 'sendIDHere');
  data.append('name', 'sendNameHere');
  data.append('image', image);

  fetch('/apiToReceiveImage', {
    method: 'POST',    
    body: data
  }).then(async (_res) => {
    const result = await _res.json();
    console.log(result);
  });
});

请记住,所有属性都应附加在图像之前

相关问题