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

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

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:

当我尝试使用带有POST请求的表单将图像上传到后端时我收到了403错误我尝试将X-CSRFToken和"Accept": "application/json"添加到标头中但一点帮助也没有我尝试从本地存储中保存的名称向postBody添加所有者但不知道我犯了什么错误我使用dj-rest-auth进行身份验证
前端有一个fetch功能

export async function action({ request }) { 
    const data = await request.formData();
    // const file = fileToBase64(data.get('file'))
    console.log(data)
    const postData = { 
      title: data.get('title'),
      image: data.get('base64File'),
    };
    console.log(postData)
    const response = await fetch('http://127.0.0.1:8000/posts', {
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(postData),
    });
    if (response.status === 422 || response.status === 401) {
      
      return response;
    }
  
    if (!response.ok) {
      throw json({ message: 'Could not add image.' }, { status: 500 });
    }
    
    
    const resData = await response.json();
    console.log(resData)
    return redirect('/');
  }

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:

export async function action({ request }) { 
    const data = await request.formData();
    // const file = fileToBase64(data.get('file'))
    console.log(data)
    const postData = { 
      title: data.get('title'),
      image: data.get('base64File'),
    };
    console.log(postData)
    const response = await fetch('http://127.0.0.1:8000/posts', {
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(postData),
    });
    if (response.status === 422 || response.status === 401) {
      
      return response;
    }
  
    if (!response.ok) {
      throw json({ message: 'Could not add image.' }, { status: 500 });
    }
  
    
    const resData = await response.json();
    console.log(resData)
    return redirect('/');
  }

There is backend serializer:

class PostsSerializer(serializers.HyperlinkedModelSerializer):
    title = serializers.CharField(max_length=60, )
    owner = serializers.ReadOnlyField(source='owner.username')
    # creator_id = UserSerializer(many=False, read_only=True).data
    favorites = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='favorite-detail')
    comments = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='comment-detail')

    class Meta:
        model = Post
        fields = ['pk', 'url', 'title', 'owner', 'image', 'created_at', 'favorites', 'comments']

And view:

class PostList(generics.ListCreateAPIView):

permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsCurrentUserOwnerOrReadOnly]
queryset = Post.objects.all()
serializer_class = PostsSerializer
ordering_fields = ['created_at', 'favorites']
filter_fields = ['title']
search_fields = ['title']
name = 'post-list'

def perform_create(self, serializer):
    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" 的输入字段,以允许用户选择要上传的图像文件。

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="image">
  <input type="submit" value="Upload">
</form>
const express = require('express');
const multer = require('multer');

const app = express();

// 配置 multer 以将上传的文件存储在 "uploads" 目录中
const upload = multer({ dest: 'uploads/' });

// 处理上传图像的 POST 请求
app.post('/upload', upload.single('image'), (req, res) => {
  const image = req.file;
  // 处理已上传的图像文件
  res.send('图像上传成功');
});
英文:

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

&lt;form action=&quot;/upload&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
  &lt;input type=&quot;file&quot; name=&quot;image&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Upload&quot;&gt;
&lt;/form&gt;


const express = require(&#39;express&#39;);
const multer = require(&#39;multer&#39;);

const app = express();

// Configure multer to store uploaded files in the &quot;uploads&quot; directory
const upload = multer({ dest: &#39;uploads/&#39; });

// Handle the POST request to upload an image
app.post(&#39;/upload&#39;, upload.single(&#39;image&#39;), (req, res) =&gt; {
  const image = req.file;
  // Do something with the uploaded image file
  res.send(&#39;Image uploaded successfully&#39;);
});

答案2

得分: 0

I solved the problem by editing the request:

export async function action({ request }) { 
    const data = await request.formData();
    // const file = fileToBase64(data.get('file'))
    console.log(data)
    const postData = { 
        title: data.get('title'),
        image: data.get('base64File')
    };
    console.log(postData)
    const response = await fetch('http://127.0.0.1:8000/posts', {
        method: 'POST',
        headers: {
            'Authorization': 'Token ' + localStorage.getItem('token'),
            "X-CSRFToken": Cookies.get('csrftoken'),
            "Accept": "application/json",
            "Content-Type": "application/json"
        },
        body: JSON.stringify(postData),
    });
    if (response.status === 422 || response.status === 401) {
        return response;
    }
  
    if (!response ok) {
        throw json({ message: 'Could not add image.' }, { status: 500 });
    }
    
    const resData = await response.json();
    console.log(resData)
    return redirect('/');
}

And by editing the settings file on the backend:

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
        'rest_framework.filters.OrderingFilter',
        'rest_framework.filters.SearchFilter',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}
REST_USE_JWT = True 
JWT_AUTH_COOKIE_USE_CSRF = True
英文:

I solved the problem by editing the request:

 export async function action({ request }) { 
    const data = await request.formData();
    // const file = fileToBase64(data.get(&#39;file&#39;))
    console.log(data)
    const postData = { 
      title: data.get(&#39;title&#39;),
      image: data.get(&#39;base64File&#39;)
    };
    console.log(postData)
    const response = await fetch(&#39;http://127.0.0.1:8000/posts&#39;, {
      method: &#39;POST&#39;,
      headers: {
        &#39;Authorization&#39;: &#39;Token &#39; + localStorage.getItem(&#39;token&#39;),
        &quot;X-CSRFToken&quot;: Cookies.get(&#39;csrftoken&#39;),
        &quot;Accept&quot;: &quot;application/json&quot;,
        &quot;Content-Type&quot;: &quot;application/json&quot;
      },
      body: JSON.stringify(postData),
    });
    if (response.status === 422 || response.status === 401) {
      
      return response;
    }
  
    if (!response.ok) {
      throw json({ message: &#39;Could not add image.&#39; }, { status: 500 });
    }
  
    
    const resData = await response.json();
    console.log(resData)
    return redirect(&#39;/&#39;);
  }

And by editing the settings file on the backend:

REST_FRAMEWORK = {
    &#39;DEFAULT_FILTER_BACKENDS&#39;: (
        &#39;django_filters.rest_framework.DjangoFilterBackend&#39;,
        &#39;rest_framework.filters.OrderingFilter&#39;,
        &#39;rest_framework.filters.SearchFilter&#39;,
    ),
    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (
        &#39;rest_framework.authentication.TokenAuthentication&#39;,
        &#39;rest_framework.authentication.SessionAuthentication&#39;,
    )
}
REST_USE_JWT = True 
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:

确定