Django Rest Framework-提交的数据不是文件。检查表单上的编码类型

时间:2018-11-28 10:22:34

标签: reactjs django-rest-framework axios

我有一篇关于文本字段的React Axios帖子,但是现在我正试图在模型中添加图像字段。

这是我的新模型,其中包含图片字段:

def get_image_path(instance, filename):
    return os.path.join('posts', str(instance.author), filename)


class TripReport(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    countries = models.ManyToManyField(Country, blank=False, related_name='trip_countries')
    title = models.CharField(max_length=100)
    content = models.TextField()
    image = models.ImageField(upload_to=get_image_path, null=True, blank=False)
    date_posted = models.DateTimeField(default=timezone.now)
    slug = models.SlugField(max_length=12, unique=True, blank=True)
    favoriters = models.ManyToManyField(User, related_name='favoriters')

我正在使用以下方法将文件从表单中拉出:

e.target.image.files[0]

它记录如下文件对象:

{ name: "DSCF6638.JPG", lastModified: 1340012616000, webkitRelativePath: "", size: 5395895, type: "image/jpeg" } 

当我进行控制台登录时。

我已将image变量添加到axios中的POST请求中:

export const postTripReport = (author, title, content, countries, image) => {
  const token = localStorage.getItem('token');
  return dispatch => {
    dispatch(postTripReportsPending());
    axios.post(
      'http://localhost:8000/api/v1/reports/',
      {
        title: title,
        content: content,
        author: author,
        countries: countries,
        image: image
      },
      {headers: { 'Authorization': `Token ${token}`}}
    )
      .then(response => {
        dispatch(postTripReportsFulfilled(response.data));
      })
      .catch(err => {
        dispatch(postTripReportsRejected());
        dispatch({type: "ADD_ERROR", error: err});
      })
  }
}

我对此并不陌生,所以我不确定当前表单的编码方式。这只是一个简单的输入:

   <input
      name='image'
      accept="image/*"
      id="flat-button-file"
      multiple={false}
      type="file"
    />

我尝试将multipart / forms-data标头添加到axios请求中,但是随后它说没有文件上传,其他所有字段均为空白。谢谢!

1 个答案:

答案 0 :(得分:5)

您可以将数据放在FormData对象中,而不是使用常规对象。这样,axios将以multipart/form-data而不是JSON的形式发送数据。

const formData = FormData();

formData.append("title", title);
formData.append("content", content);
formData.append("author", author);
formData.append("countries", countries);
formData.append("image", image);

axios.post("http://localhost:8000/api/v1/reports/", formData, {
  headers: { Authorization: `Token ${token}` }
});