当我在POST请求中上传Base64图像时,我收到403错误。

huangapple go评论104阅读模式
英文:

When I upload image as base64 in post request I get error 403

问题

I've translated the code-related part of your text. Here it is:

  1. 当我尝试使用带有POST请求的表单将图像上传到后端时我收到了403错误我尝试将X-CSRFToken"Accept": "application/json"添加到标头中但一点帮助也没有我尝试从本地存储中保存的名称向postBody添加所有者但不知道我犯了什么错误我使用dj-rest-auth进行身份验证
  2. 前端有一个fetch功能
  3. export async function action({ request }) {
  4. const data = await request.formData();
  5. // const file = fileToBase64(data.get('file'))
  6. console.log(data)
  7. const postData = {
  8. title: data.get('title'),
  9. image: data.get('base64File'),
  10. };
  11. console.log(postData)
  12. const response = await fetch('http://127.0.0.1:8000/posts', {
  13. method: 'POST',
  14. headers: {
  15. "Content-Type": "application/json"
  16. },
  17. body: JSON.stringify(postData),
  18. });
  19. if (response.status === 422 || response.status === 401) {
  20. return response;
  21. }
  22. if (!response.ok) {
  23. throw json({ message: 'Could not add image.' }, { status: 500 });
  24. }
  25. const resData = await response.json();
  26. console.log(resData)
  27. return redirect('/');
  28. }

Please note that I've retained the code formatting in the translation. If you have further code-related questions or need translations for other parts of your text, please feel free to ask.

英文:

When I try to upload an image to the backend using a form with post request, I get a 403 error. I tried adding X-CSRFToken and "Accept": "application/json" to the headers, it didn't help at all. I tried to add the owner to the postBody from the name that I was saving to the localstorage
I don't know where I made a mistake. I use dj-rest-auth for authentication
There is fetch function from frontend:

  1. export async function action({ request }) {
  2. const data = await request.formData();
  3. // const file = fileToBase64(data.get('file'))
  4. console.log(data)
  5. const postData = {
  6. title: data.get('title'),
  7. image: data.get('base64File'),
  8. };
  9. console.log(postData)
  10. const response = await fetch('http://127.0.0.1:8000/posts', {
  11. method: 'POST',
  12. headers: {
  13. "Content-Type": "application/json"
  14. },
  15. body: JSON.stringify(postData),
  16. });
  17. if (response.status === 422 || response.status === 401) {
  18. return response;
  19. }
  20. if (!response.ok) {
  21. throw json({ message: 'Could not add image.' }, { status: 500 });
  22. }
  23. const resData = await response.json();
  24. console.log(resData)
  25. return redirect('/');
  26. }

There is backend serializer:

  1. class PostsSerializer(serializers.HyperlinkedModelSerializer):
  2. title = serializers.CharField(max_length=60, )
  3. owner = serializers.ReadOnlyField(source='owner.username')
  4. # creator_id = UserSerializer(many=False, read_only=True).data
  5. favorites = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='favorite-detail')
  6. comments = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='comment-detail')
  7. class Meta:
  8. model = Post
  9. fields = ['pk', 'url', 'title', 'owner', 'image', 'created_at', 'favorites', 'comments']

And view:

  1. class PostList(generics.ListCreateAPIView):
  2. permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsCurrentUserOwnerOrReadOnly]
  3. queryset = Post.objects.all()
  4. serializer_class = PostsSerializer
  5. ordering_fields = ['created_at', 'favorites']
  6. filter_fields = ['title']
  7. search_fields = ['title']
  8. name = 'post-list'
  9. def perform_create(self, serializer):
  10. serializer.save(owner=self.request.user)

If you need the full code here is a link to the repository: https://github.com/Cichyy22/imagur-like-site

答案1

得分: 0

在你的表单中包括一个类型为 "file" 的输入字段,以允许用户选择要上传的图像文件。

  1. <form action="/upload" method="post" enctype="multipart/form-data">
  2. <input type="file" name="image">
  3. <input type="submit" value="Upload">
  4. </form>
  1. const express = require('express');
  2. const multer = require('multer');
  3. const app = express();
  4. // 配置 multer 以将上传的文件存储在 "uploads" 目录中
  5. const upload = multer({ dest: 'uploads/' });
  6. // 处理上传图像的 POST 请求
  7. app.post('/upload', upload.single('image'), (req, res) => {
  8. const image = req.file;
  9. // 处理已上传的图像文件
  10. res.send('图像上传成功');
  11. });
英文:

Include an input field of type "file" in your form to allow the user to select an image file to upload.

  1. &lt;form action=&quot;/upload&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
  2. &lt;input type=&quot;file&quot; name=&quot;image&quot;&gt;
  3. &lt;input type=&quot;submit&quot; value=&quot;Upload&quot;&gt;
  4. &lt;/form&gt;
  5. const express = require(&#39;express&#39;);
  6. const multer = require(&#39;multer&#39;);
  7. const app = express();
  8. // Configure multer to store uploaded files in the &quot;uploads&quot; directory
  9. const upload = multer({ dest: &#39;uploads/&#39; });
  10. // Handle the POST request to upload an image
  11. app.post(&#39;/upload&#39;, upload.single(&#39;image&#39;), (req, res) =&gt; {
  12. const image = req.file;
  13. // Do something with the uploaded image file
  14. res.send(&#39;Image uploaded successfully&#39;);
  15. });

答案2

得分: 0

I solved the problem by editing the request:

  1. export async function action({ request }) {
  2. const data = await request.formData();
  3. // const file = fileToBase64(data.get('file'))
  4. console.log(data)
  5. const postData = {
  6. title: data.get('title'),
  7. image: data.get('base64File')
  8. };
  9. console.log(postData)
  10. const response = await fetch('http://127.0.0.1:8000/posts', {
  11. method: 'POST',
  12. headers: {
  13. 'Authorization': 'Token ' + localStorage.getItem('token'),
  14. "X-CSRFToken": Cookies.get('csrftoken'),
  15. "Accept": "application/json",
  16. "Content-Type": "application/json"
  17. },
  18. body: JSON.stringify(postData),
  19. });
  20. if (response.status === 422 || response.status === 401) {
  21. return response;
  22. }
  23. if (!response ok) {
  24. throw json({ message: 'Could not add image.' }, { status: 500 });
  25. }
  26. const resData = await response.json();
  27. console.log(resData)
  28. return redirect('/');
  29. }

And by editing the settings file on the backend:

  1. REST_FRAMEWORK = {
  2. 'DEFAULT_FILTER_BACKENDS': (
  3. 'django_filters.rest_framework.DjangoFilterBackend',
  4. 'rest_framework.filters.OrderingFilter',
  5. 'rest_framework.filters.SearchFilter',
  6. ),
  7. 'DEFAULT_AUTHENTICATION_CLASSES': (
  8. 'rest_framework.authentication.TokenAuthentication',
  9. 'rest_framework.authentication.SessionAuthentication',
  10. )
  11. }
  12. REST_USE_JWT = True
  13. JWT_AUTH_COOKIE_USE_CSRF = True
英文:

I solved the problem by editing the request:

  1. export async function action({ request }) {
  2. const data = await request.formData();
  3. // const file = fileToBase64(data.get(&#39;file&#39;))
  4. console.log(data)
  5. const postData = {
  6. title: data.get(&#39;title&#39;),
  7. image: data.get(&#39;base64File&#39;)
  8. };
  9. console.log(postData)
  10. const response = await fetch(&#39;http://127.0.0.1:8000/posts&#39;, {
  11. method: &#39;POST&#39;,
  12. headers: {
  13. &#39;Authorization&#39;: &#39;Token &#39; + localStorage.getItem(&#39;token&#39;),
  14. &quot;X-CSRFToken&quot;: Cookies.get(&#39;csrftoken&#39;),
  15. &quot;Accept&quot;: &quot;application/json&quot;,
  16. &quot;Content-Type&quot;: &quot;application/json&quot;
  17. },
  18. body: JSON.stringify(postData),
  19. });
  20. if (response.status === 422 || response.status === 401) {
  21. return response;
  22. }
  23. if (!response.ok) {
  24. throw json({ message: &#39;Could not add image.&#39; }, { status: 500 });
  25. }
  26. const resData = await response.json();
  27. console.log(resData)
  28. return redirect(&#39;/&#39;);
  29. }

And by editing the settings file on the backend:

  1. REST_FRAMEWORK = {
  2. &#39;DEFAULT_FILTER_BACKENDS&#39;: (
  3. &#39;django_filters.rest_framework.DjangoFilterBackend&#39;,
  4. &#39;rest_framework.filters.OrderingFilter&#39;,
  5. &#39;rest_framework.filters.SearchFilter&#39;,
  6. ),
  7. &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (
  8. &#39;rest_framework.authentication.TokenAuthentication&#39;,
  9. &#39;rest_framework.authentication.SessionAuthentication&#39;,
  10. )
  11. }
  12. REST_USE_JWT = True
  13. JWT_AUTH_COOKIE_USE_CSRF = True

huangapple
  • 本文由 发表于 2023年3月31日 21:36:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定