前提・実現したいこと
お世話になっております。初歩的なご質問かもしれず、大変恐縮ではございますが、ご質問させていただきます。
実現したいことは、
フロント側(React)から、ボタンをクリックしたときに、ファイル(例えばPDFファイルやワードファイルなど)のデータをAxiosで、バックエンドのDjangoに送り、DBに登録したい、というものです。
Djangoのデフォルト管理画面からは、ファイルデータの登録ができて、データベースに反映されていますので、フロント側から送る際に間違っている、と考えております。
React, Typescriptで書いております
発生している問題・エラーメッセージ
エラーメッセージ 以下のコードで実行すると、 POST 400 (Bad Request)が表示され、エラーの中身が以下でございます。 「Multipart form parse error - Invalid boundary in multipart: None」とエラー出ているようでございます。 data: detail: "Multipart form parse error - Invalid boundary in multipart: None" [[Prototype]]: Object headers: content-length: "77" content-type: "application/json" [[Prototype]]: Object request: XMLHttpRequest onabort: ƒ handleAbort() onerror: ƒ handleError() onload: null onloadend: null onloadstart: null onprogress: null onreadystatechange: ƒ handleLoad() ontimeout: ƒ handleTimeout() readyState: 4 response: "{\"detail\":\"Multipart form parse error - Invalid boundary in multipart: None\"}" responseText: "{\"detail\":\"Multipart form parse error - Invalid boundary in multipart: None\"}" responseType: "" responseXML: null status: 400 statusText: "Bad Request" timeout: 0 upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …} withCredentials: false [[Prototype]]: XMLHttpRequest status: 400 statusText: "Bad Request"
該当のソースコード
// フロント側、React Typescriptでございます。 export const fetchAsyncCreateFile = createAsyncThunk( "potentialDeal/createFile", async (uploadingfile: FILE) => { console.log(uploadingfile) let formData = new FormData() formData.append('file', uploadingfile); const res = await axios.post<FILE>( `${process.env.REACT_APP_API_URL}/api/files/`, { formData, }, { headers: { // "Content-Type": "application/json", 'Content-Type': 'multipart/form-data', Authorization: `JWT ${localStorage.localJWT}`, } } ) .then(response => { console.log(response) }) .catch(error => { console.log(error.response) }) // return res.data } ) // formData.append で渡しているデータ(console.log(uploadingfile))は以下でございます。ワードファイルを渡した場合です File {name: "wordfile.docx", lastModified: 1630541701576, lastModifiedDate: Thu Sep 02 2021 09:15:01 GMT+0900 (日本標準時), webkitRelativePath: "", size: 11969, …} lastModified: 1630541701576 lastModifiedDate: Thu Sep 02 2021 09:15:01 GMT+0900 (日本標準時) {} name: "wordfile.docx" size: 11969 type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" webkitRelativePath: "" [[Prototype]]: File // 関係ないと思うのですが、バックエンド側のコードがこちらでございます Django views.py class FileViewSet(viewsets.ModelViewSet): queryset = File.objects.all() serializer_class = FileSerializer # def perform_create(self, serializer): # serializer.save(user_id=self.request.user) Django models.py class File(models.Model): file = models.FileField( # blank=True, # null=True, upload_to=upload_file_path, verbose_name='関連ファイル' user_id = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='files', on_delete=models.CASCADE, blank=True, null=True, ) dealpotential_id = models.ForeignKey( DealPotential, related_name='files', on_delete=models.CASCADE, blank=True, null=True, ) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file.url Django serializers.py class FileSerializer(serializers.ModelSerializer): created_on = serializers.DateTimeField(format="%Y-%m-%d %H:%M", read_only=True) class Meta: model = File fields = ('id', 'file', 'user_id', 'dealpotential_id', 'created_on') Django /urls.py (略) router = routers.DefaultRouter() router.register('files', FileViewSet) (略)
試したこと
Content-typeが、"Content-Type": "application/json", で実行している例も発見したため、こちらでも試していますが、ダメでした。
response: "{"file":["No file was submitted."]}"
responseText: "{"file":["No file was submitted."]}"
こちらの場合、このエラーが出ています。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/09/03 23:46
退会済みユーザー
2021/09/04 03:38