'Django REST: Files\Images Uploading
Im want to upload an image using Vue.js and Django-rest. And have few problems with it.
Im trying to use put request (as in docs) and FileUploadParser for it, but getting an error:
detail: "Missing filename. Request should include a Content-Disposition header with a filename parameter.
If i make my header like:
'Content-type':'multipart/form-data',
'filename': 'file'
Django registers request as OPTIONS, not put, so my put function not called.
My serializer:
class ImagesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Images
fields = ('image',)
My view:
class ImagesViewSet(APIView):
parser_classes = (FileUploadParser,)
def get(self, request):
images = Images.objects.all()
serializer = ImagesSerializer(images, many=True)
return Response(serializer.data)
def put(self, request, filename, format=None):
image = request.data['image']
Images.objects.create(
image=image
)
return Response(status=204)
My Vue.js request:
import axios from 'axios';
export default {
name: 'App',
data(){
return {
name: '',
image: '',
description: '',
price: '',
files: false,
}
},
methods: {
onFileChange(e) {
console.log('works');
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
createNewProduct(){
const config = {
headers: {
'Content-type':'multipart/form-data',
'filename': 'file'
}
}
let formData = new FormData();
formData.append('image', this.image);
axios.put('http://127.0.0.1:8000/images/',{
formData
}, config).then(response => {
console.log('Success');
this.$router.push('/')
}, response => {
console.log('FAIL');
});
}
}
}
What im doing wrong, or what did i miss?
Solution 1:[1]
In addition to the Content-Type
header, you're going to want to add a content-disposition header, like so:
headers: {
'Content-type':'multipart/form-data',
'Content-Disposition': 'attachment; filename=file',
'filename': 'file'
}
Solution 2:[2]
File uploading in Django REST framework is the same with uploading files in multipart/form in django.
To test it you can use curl:
curl -X POST -H "Content-Type:multipart/form-data" -u {username}:{password} \
-F "{field_name}=@{filename};type=image/jpeg" http://{your api endpoint}
You can try solution find here on stackoverflow
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AlTheOne |
Solution 2 |