【问题标题】:GETTING ERROR POSTING FILE TO MYSQL - PHP-CRUD-API将文件发布到 MYSQL 时出错 - PHP-CRUD-API
【发布时间】:2021-09-18 23:26:06
【问题描述】:

我正在尝试使用 mevdschee 的 PHP-CRUD-API 上传图像。 我几乎什么都试过了。。 这些是我尝试过的服务功能,使用 FormData 或简单的 json。

service.ts

addMapIcon(mapIcon:mapIcon): Observable<string>{
    let fd = new FormData;
    fd.append('active', mapIcon.active?'1':'0');
    fd.append('file',mapIcon.file);
    fd.append('name',mapIcon.name);
    return this.http.post<string>(this.iconApiUrl, fd);

..or even:

    return this.http.post<string>(this.iconApiUrl, fd, {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Content-type':'multipart/form-data'
          + combination of others parameters
          }));
    
  }
addMapIcon(mapIcon:mapIcon): Observable<string>{
      return this.http.post<string>(this.iconApiUrl, mapIcon, {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          }),
        });  
      }

组件.ts

onIconChange(e) {
    const reader = new FileReader();
    
    if(e.target.files && e.target.files.length) {
      const [file] = e.target.files;
      reader.readAsDataURL(file);
    
      reader.onload = () => {
        this.mapIcon.file = file; //(or even reader.result as string; as found in some example)
        this.mapIcon.name = file.name;
        this.mapIcon.active = true;
        //this.icon.file = file;
        /*this.uploadForm.patchValue({
          imgSrc: reader.result
        });*/
   
      };
    }
  }

文件字段在mysql中定义为mediumblob。

我得到的错误是“数据完整性违规”

无法理解错误在哪里..

【问题讨论】:

  • 如果您要发布错误消息,请将其全部发布。您的 MySQL 架构似乎有问题,但您只发布了部分错误消息,没有发布任何相关代码或表结构。
  • 我正在使用 mevdschee 的 treeql PDO PHP-CRUD-API,我得到的唯一消息是 1010 - “数据完整性违规”。
  • treeql.org/learn,搜索 1010,是一个冲突。我正在尝试通过招摇来发布,但再次得到错误。如果我在文件字段中放一个小字符串(通过招摇),我只能发布

标签: php angular http-post


【解决方案1】:

“数据完整性违规”错误是由失败的约束引起的。这可能是:

  • 外键约束失败(引用的记录不存在)
  • 缺少字段值(在没有默认值的字段上)
  • 一个不允许的空值(该字段不可为空)

您可以启用调试模式(配置中的'debug' =&gt; true)并查看响应的X-Exception-Message HTTP 标头(使用浏览器开发者工具的网络选项卡)。它将包含问题的原因。

注意:我是“mevdschee”,PHP-CRUD-API 的作者。

【讨论】:

  • 我已经查看了如何在文档中启用调试..但没有发现..我的错误。非常感谢你
  • @NikRubblers 如果它帮助您解决问题,请接受答案。
【解决方案2】:

您能否使用 post 请求成功地将图像 blob 发送到后端?如果不试试这个:

addMapIcon(mapIcon:mapIcon): Observable<string>{
    let fd = new FormData();
    fd.append('active', mapIcon.active?'1':'0');
    **fd.append('file',mapIcon.file, mapIcon.name);**
    fd.append('name',mapIcon.name);

    return this.http.post<string>(this.iconApiUrl, fd, {
        headers: new HttpHeaders({
          'Content-type':'multipart/form-data'
          }));
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2015-06-27
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多