我使用react Js将图像上传到django restframework。 在这里,我使用fetch API发送帖子请求。
Eapp.jsx
import React, { Component } from 'react';
class Eapp extends Component {
constructor(props){
super(props);
this.state = {
profilePic: null,
};
this.inpuElement = null;
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e){
this.setState({profilePic: e.target.files[0]});
}
handleSubmit(){
let formData = new FormData();
formData.append('profile_pic',this.state.profilePic);
fetch('http://10.42.0.1:8000/auth/profile-pic/', {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'content-type': 'multipart/form-data',
},
body:formData,
}).then(res => res.json())
.then((data) => {
console.log(data);
})
.catch(err => console.log(err));
}
render(){
return(
<div>
<input
type="file"
multiple={false}
ref={(input) => { this.inpuElement = input; }}
accept=".jpg,.jpeg,.png"
onChange={this.handleChange}
/>
<button onClick={this.handleSubmit}>submit</button>
</div>
);
}
}
export default Eapp;
错误消息
Eapp.jsx:19 POST http://10.42.0.1:8000/auth/profile-pic/ 500 (Internal Server Error)
handleSubmit @ Eapp.jsx:19
callCallback @ react-dom.development.js:542
invokeGuardedCallbackDev @ react-dom.development.js:581
invokeGuardedCallback @ react-dom.development.js:438
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452
executeDispatch @ react-dom.development.js:836
executeDispatchesInOrder @ react-dom.development.js:858
executeDispatchesAndRelease @ react-dom.development.js:956
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967
forEachAccumulated @ react-dom.development.js:935
processEventQueue @ react-dom.development.js:1112
runEventQueueInBatch @ react-dom.development.js:3607
handleTopLevel @ react-dom.development.js:3616
handleTopLevelImpl @ react-dom.development.js:3347
batchedUpdates @ react-dom.development.js:11082
batchedUpdates @ react-dom.development.js:2330
dispatchEvent @ react-dom.development.js:3421
example:1 Failed to load http://10.42.0.1:8000/auth/profile-pic/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Eapp.jsx:30 TypeError: Failed to fetch
django的
views.py
class ProfilePictureView(generics.CreateAPIView):
permission_classes = (permissions.AllowAny,)
serializer_class = ProfilePictureSerializer
parser_classes = (parsers.FormParser,parsers.MultiPartParser, parsers.FileUploadParser, )
def perform_create(self, serializer):
print(self.request.FILES['profile_pic'])
serializer.save(user=User.objects.get(pk=2))
models.py
class Person(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(null=True, upload_to='media')
face_encodings = models.BinaryField(null=True)
def __str__(self):
return str(self.user.first_name)
serializers.py
class ProfilePictureSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ['profile_pic','user']
read_only_fields = ('user',)
class ProfilePictureSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ['profile_pic','user']
read_only_fields = ('user',)
class ProfilePictureSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ['profile_pic','user']
read_only_fields = ('user',)
raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary.decode())
AttributeError: 'NoneType' object has no attribute 'decode'
我已经包含了django cors标头,除了这个之外,每个其他的api路由都在工作。我尝试了不同的发布请求方法,但仍然遇到了错误。 它似乎没有访问服务器,因为每个其他路由都在工作。 我在django中尝试过MultiPart解析器fileUpload解析器,但仍然有错误状态400,500。
答案 0 :(得分:4)
尝试在标题中没有内容类型,这肯定会有所帮助。
答案 1 :(得分:0)
尝试
"Content-Type":"multipart/form-data"
在handleSubmit函数中!