I'm trying to upload a file via Fetch, to a Django REST endpoint.
Component with Fetch Code:
function myComponent(props) {
const classes = useStyles();
const [{token}] = useContext();
function handleImageUpload(files) {
let formData = new FormData()
formData.append('file', files[0])
fetch(receiveSpreadsheetEndpoint, {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
})
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => {
console.error(error)
})
}
function Dropzone(props) {
const [files, setFiles] = useState([]);
function handleChange(event) {
setFiles(event[0]);
}
return (
<>
<DropzoneArea
onChange={event => handleChange(event)}
/>
<Button
variant="contained"
color="primary"
onClick={event => handleImageUpload([files])}
>
Primary
</Button>
</>
)
}
return (
<Container className={classes.root} height="100%">
<Dropzone
acceptedFiles={['.csv', 'text/*', 'text/csv']}
showPreviews={true}
showFileNamesInPreview={true}
/>
</Container>
);
}
Django REST endpoint:
class ReceiveFileData(APIView):
permission_classes = (IsAuthenticated,)
parser_classes = (JSONParser, FormParser, MultiPartParser)
def post(self, request):
my_file = request.stream.read
data = {} <== a breakpoint is set here
return Response(data, status=status.HTTP_200_OK)
After my_file = request.stream.read, my_file contains b''.
What am I leaving out?
UPDATE
Here's the request object when it arrives at the REST endpoint on the server:
