发送图片和字符串表

时间:2019-05-27 00:03:55

标签: angular

创建帖子时,用户还可以上传图像。所有数据都通过使用Django REST框架构建的REST API发送到数据库。

我收到此错误inr图片 提交的数据不是文件。检查表单上的编码类型。

服务

addPosts(title: string, content: string, image: File, category: string, tags: string[]){
   let url = 'api/posts/post/';
   const formData = new FormData();

   formData.append("title", title);
   formData.append("content", content);
   formData.append("category", category);
   formData.append("tags", tags);
   formData.append("image", image);

   const post: Post = {title:title, content:content, image: image, category:category, tags:tags};

   let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
   let options = new RequestOptions({ headers: headers });

   this.http.post(url, post, options)
   .subscribe(responseData => {
     this.posts.push(post);
     this.postsUpdate.next([...this.posts]);
   });
 }

当我使用FormData时,我无法发送标签,因为我认为FormData不支持它,而当我直接发送帖子时,我得到了 提交的数据不是文件。检查表单上的编码类型。

1 个答案:

答案 0 :(得分:0)

addPosts(title: string, content: string, image: File, category: string, tags: string[]){
   let url = 'api/posts/post/';
   const formData = new FormData();

   formData.append("title", title);
   formData.append("content", content);
   formData.append("category", category);
   formData.append("tags", tags);
   formData.append("image", image);

   const post: Post = {title:title, content:content, image: image, category:category, tags:tags};<------you set This

   let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
   let options = new RequestOptions({ headers: headers });

设置formData

  this.http.post(url, post, options)<-----set Form Data instead of ` const post: Post`
   .subscribe(responseData => {
     this.posts.push(post);
     this.postsUpdate.next([...this.posts]);
   });
 }