为了账号安全,请及时绑定邮箱和手机立即绑定

将带有离子/角度的图像上传到php脚本不起作用

将带有离子/角度的图像上传到php脚本不起作用

PHP
Smart猫小萌 2022-09-17 22:08:13
我正在尝试使我的Ionic应用程序上传用户选择的图像。我阅读了几个教程,但是我没有设法使它工作。我希望应用程序在浏览器中运行,因此我没有实现仅在移动平台上运行的解决方案。我的 angular 组件将发布请求发送到托管以下 php 脚本的服务器,并按指定创建“uploads”文件夹。但是每次我想上传我的文件时,我都会收到“上传文件时出错,请重试!”消息,在我的PHP脚本中指定。我想我可能以错误的格式发送数据,但是可以弄清楚该怎么做。任何想法,我的问题可能是什么?<?phpheader('Access-Control-Allow-Origin: *');$target_path = "uploads/";$target_path = $target_path . basename( $_FILES['file']['name']);if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {    header('Content-type: application/json');    $data = ['success' => true, 'message' => 'Upload and move success'];    echo json_encode( $data );} else{    header('Content-type: application/json');    $data = ['success' => false, 'message' => 'There was an error uploading the file, please try again!'];    echo json_encode( $data );}?>这是我的组件中的类型脚本代码:import { Component, OnInit, ChangeDetectorRef } from '@angular/core';import { HttpClient } from '@angular/common/http';@Component({  selector: 'app-erledigt-modal',  templateUrl: './erledigt-modal.component.html',  styleUrls: ['./erledigt-modal.component.scss'],})export class ErledigtModalComponent implements OnInit {   constructor(private http: HttpClient) { }  selectedFile = null;  ngOnInit() {  }  onFileChanged(event) {      this.selectedFile = <File>event.target.files[0]  }  onUpload() {    const uploadData = new FormData();    uploadData.append('image', this.selectedFile, this.selectedFile.name);    this.http.post('https://...MyAPI.../upload.php', uploadData).subscribe(res => {      console.log(res);    });  }}我还尝试了以下POST请求,但没有成功:this.http.post('https://...MyAPI.../upload.php', this.selectedFile).subscribe(res => {      console.log(res);});  } 我的 HTML 看起来很简单:<input type="file" (change)="onFileChanged($event)"><button type="button" (click)="onUpload()">Upload</button>
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

我找到了解决方案...

if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path))

uploadData.append('image', this.selectedFile, this.selectedFile.name);

不要一起工作,因为我在表单数据中使用的名称是“图像”,而PHP脚本需要“文件”。所以将“图像”更改为“文件”是解决方案...


查看完整回答
反对 回复 2022-09-17
  • 1 回答
  • 0 关注
  • 131 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号