Javascript 为什么上传的图像文件在提交表单时显示为空?反应js
我试图使用axios在react js和django api中上传图像,但当我上传图像时,它会在请求中显示文件Javascript 为什么上传的图像文件在提交表单时显示为空?反应js,javascript,reactjs,axios,Javascript,Reactjs,Axios,我试图使用axios在react js和django api中上传图像,但当我上传图像时,它会在请求中显示文件{}。我只想上传带有类别的图片,当我选择类别时,它在仅请求文件shows{}中显示,我尝试了很多,但都没有成功,所以请指导我如何让它成功。这是我的代码,我试过了。谢谢 import React, { Component } from "react"; import { Helmet } from "react-helmet"; import { w
{}
。我只想上传带有类别的图片,当我选择类别时,它在仅请求文件shows{}
中显示,我尝试了很多,但都没有成功,所以请指导我如何让它成功。这是我的代码,我试过了。谢谢
import React, { Component } from "react";
import { Helmet } from "react-helmet";
import { withTranslation } from "react-i18next";
import config from "../../Main";
import arrow_left from "../../../img/Aarrow.png";
import Swal from "sweetalert2";
import axios from "axios";
let authToken = localStorage.getItem("Token");
class EditCar extends Component {
constructor(props) {
super(props);
this.state = {
car_photo: [
{
category: "",
sub_category: "",
file: null,
},
]
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleImage = this.handleImage.bind(this)
}
handleSubmit(e) {
e.preventDefault();
const data = {
car_photo: [
...this.state.car_photo.map((c) => ({
category: c.category,
sub_category: c.sub_category,
file: c.file,
})),
],
};
axios({
method: "PUT",
url: `${config.apiUrl.car}${this.props.match.params.pk}/profile/`,
headers: {
Accept: "application/json, application/xml, text/plain, text/html, *.*",
//"Content-Type": "multipart/form-data",
"Content-Type": "application/json",
// "Content-Disposition": "attachment; filename=file",
Authorization: "Bearer " + JSON.parse(authToken),
},
data,
})
.then((res) => {
Swal.fire({
title: "Car",
type: "success",
text: "Car Update Successfully !",
showConfirmButton: false,
timer: 2000,
});
})
.catch((err) => {
Swal.fire({
title: "Car",
type: "error",
text: "Error while updating new Car!",
timer: 2000,
});
});
}
componentDidMount() {
axios
.get(`${config.apiUrl.car}${this.props.match.params.pk}/profile/`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + JSON.parse(authToken),
},
})
.then((res) => {
//console.log(res);
this.setState({
car_photo: [...res.data.car_photo],
});
})
.catch((err) => {
console.log(err);
});
}
async onChange(e, index) {
if (["category", "sub_category"].includes(e.target.name)) {
let cats = [...this.state.car_photo];
cats[index][e.target.name] = e.target.value;
await this.setState({
cats,
});
} else {
this.setState({ [e.target.name]: e.target.value });
}
console.log("hello", this.props.doc);
}
async handleImage(e, index) {
if (["file"].includes(e.target.name)) {
let cats = [...this.state.car_photo];
cats[index][e.target.name] = e.target.files[0];
await this.setState({
cats,
});
} else {
this.setState({ [e.target.name]: e.target.files[0] });
}
}
render() {
const { t } = this.props;
return (
<div className="container1" style={{ marginTop: "30px" }}>
<Helmet>
<title>{t("car_metrics_edit")}</title>
</Helmet>
<div className="headerr" id="headerr" style={{ marginTop: "-6px" }}>
<form onSubmit={this.handleSubmit}>
<div >
{this.state.car_photo
.slice(0, 2)
.map((inputField, index) => (
<div className="row">
<div className="form-group">
<select
name="sub_category"
class="form-control donn"
value={inputField.sub_category}
onChange={(e) => {
this.onChange(e, index);
}}
style={{ width: "220px" }}
>
<option value="" selected display hidden>
Select Category
</option>
<option value="Registration Documentation">
Registration Documentation
</option>
<option value="Plate Number Documentation">
Plate Number doc
</option>
</select>
</div>
<div className="">
</div>
<div class="form-group">
<input
type="file"
name="file"
// value={inputField.file}
onChange={(e) => {
this.handleImage(e, index);
}}
class="form-control-file"
id="exampleFormControlFile1"
/>
</div>
</div>
))}
<div style={{ marginTop: "70px" }}>
<center>
<button
type="submit"
value="Get Data"
className="btn btn-login text-white font-weight-bolder boxx "
id="button1"
style={{
height: "40px",
fontSize: "13px",
width: "200px",
background: "rgba(183, 28, 28, 1)",
border: "none",
color: "white",
margin: "auto",
}}
>
SAVE
</button>
</center>
</div>
</div>
</form>
</div>
</div>
);
}
}
export default withTranslation()(EditCar);
import React,{Component}来自“React”;
从“react Helmet”导入{Helmet};
从“react-i18next”导入{withTranslation};
从“../../Main”导入配置;
从“../../../img/Aarrow.png”左侧导入箭头;
从“sweetalert2”导入Swal;
从“axios”导入axios;
让authToken=localStorage.getItem(“令牌”);
类EditCar扩展组件{
建造师(道具){
超级(道具);
此.state={
车照:[
{
类别:“,
亚类:“,
文件:null,
},
]
};
this.handleSubmit=this.handleSubmit.bind(this);
this.handleImage=this.handleImage.bind(this)
}
handleSubmit(e){
e、 预防默认值();
常数数据={
车照:[
…此.state.car\u photo.map((c)=>({
类别:c类,
子类别:c.子类别,
文件:c.file,
})),
],
};
axios({
方法:“放”,
url:`${config.apirl.car}${this.props.match.params.pk}/profile/`,
标题:{
接受:“application/json、application/xml、text/plain、text/html、****”,
//“内容类型”:“多部分/表单数据”,
“内容类型”:“应用程序/json”,
//“内容处置”:“附件;文件名=文件”,
授权:“承载者”+JSON.parse(authToken),
},
数据,
})
。然后((res)=>{
喷火({
标题:“汽车”,
键入:“成功”,
文本:“车辆更新成功!”,
showconfixton:false,
计时器:2000,
});
})
.catch((错误)=>{
喷火({
标题:“汽车”,
键入:“错误”,
文本:“更新新车时出错!”,
计时器:2000,
});
});
}
componentDidMount(){
axios
.get(`${config.apirl.car}${this.props.match.params.pk}/profile/`{
方法:“获取”,
标题:{
接受:“应用程序/json”,
“内容类型”:“应用程序/json”,
授权:“承载者”+JSON.parse(authToken),
},
})
。然后((res)=>{
//控制台日志(res);
这是我的国家({
汽车照片:[…res.data.car\u photo],
});
})
.catch((错误)=>{
控制台日志(err);
});
}
异步onChange(e,索引){
if([“类别”,“子类别”]包括(如目标名称)){
let cats=[…这个.state.car_照片];
cats[index][e.target.name]=e.target.value;
等待这一天({
猫,
});
}否则{
this.setState({[e.target.name]:e.target.value});
}
log(“hello”,this.props.doc);
}
异步handleImage(e,索引){
如果([“文件”].includes(e.target.name)){
let cats=[…这个.state.car_照片];
cats[index][e.target.name]=e.target.files[0];
等待这一天({
猫,
});
}否则{
this.setState({[e.target.name]:e.target.files[0]});
}
}
render(){
const{t}=this.props;
返回(
{t(“car\u metrics\u edit”)}
{this.state.car_照片
.slice(0,2)
.map((输入字段,索引)=>(
{
这一变化(e,索引);
}}
样式={{width:“220px”}
>
选择类别
登记文件
车牌号文件
{
这个.handleImage(e,索引);
}}
class=“表单控制文件”
id=“exampleFormControlFile1”
/>
))}
拯救
);
}
}
使用Translation()导出默认值(EditCar);
这里是我在提交表单后检查的console.log(data)
数据的图像。
[
以下是提交表单后请求中显示的内容的图像。
[handleSubmit方法中axios前面的console.log(数据)并查看输出。当我试图检查
console.log(数据)时,它在中显示数据。
@MrKhan