如何解决文件上传后角度显示 REST 响应
我有一个 angular 应用程序,我想上传一个文件并根据上传的文件显示一个字符串。
我对 Rest API 进行了后期调用,该 API 返回了一个响应,我想显示该响应的内容。然而,有些地方出了问题,因为我可以console.log
显示响应的内容,但我无法正常显示它(即作为标签或类似内容)。
谁能告诉我怎么做?
这是component.html
<div>
<label class="image-upload-container btn btn-bwm">
<span>Select Image</span>
<input #imageInput type="file" accept="image/*" (change)="processFile(imageInput)">
</label>
<!--IT DOES NOT WORK displays [object Object] -->
<input type=text name="prediction" [(ngModel)]="prediction" />
<!--IT DOES NOT WORK displays [object Object] -->
{{prediction}}
</div>
这里是component.ts
import { Component,OnInit } from '@angular/core';
import { ImageService } from '../../services/image.service';
class ImageSnippet {
constructor(public src: string,public file: File) { }
}
@Component({
selector: 'app-image',templateUrl: './image.component.html',styleUrls: ['./image.component.css']
})
export class ImageComponent implements OnInit {
constructor(private imageService: ImageService) { }
prediction!: String;
ngOnInit(): void {
}
processFile(imageInput: any) {
const file: File = imageInput.files[0];
const reader = new FileReader();
reader.addEventListener('load',(event: any) => {
let selectedFile = new ImageSnippet(event.target.result,file);
this.imageService.uploadImage(selectedFile.file).subscribe(
(response) => {
this.prediction = response.toString();// IT DOES NOT WORK displays [object Object]
// console.log() WORKS: it logs something like this: {prediction: "jeges,tensor([0.0530,0.0999,0.8471])"}
//which is the exact string that I want to display
console.log(response)
}
});
reader.readAsDataURL(file);
}
}
这里是service.ts
...
uploadImage(imageFile: File): Observable<Response> {
const formData = new FormData();
formData.append('imageFile',imageFile);
return this.http_client.post<Response>(this.url,formData);
}
...
这里是 API:
@app.route('/api/image-upload',methods=['POST'])
def call_predict():
imageFile = request.files['imageFile']
prediction = makePrediction(imageFile)
resp = make_response({"prediction": prediction},200)
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
解决方法
您的 toString()
上有一个 response
调用,导致显示 string
。因此,让我们从正确修复您的文件处理程序功能开始:
因此,首先像这样修复您的服务请求处理程序
this.imageService.uploadImage(selectedFile.file).subscribe(
(response) => {
this.prediction = response;
}
});
因此,此更改会导致您的 HTML 出现问题,因此我们需要对其进行调整,因为 this.prediction
不是 string
<div>
<label class="image-upload-container btn btn-bwm">
<span>Select Image</span>
<input #imageInput type="file" accept="image/*" (change)="processFile(imageInput)">
</label>
<!-- here we'll bind according to the structure you gave in your code -->
<input type=text name="prediction" [(ngModel)]="prediction.prediction"/>
<!-- Since we have an object we cant just dump it here,so lets use a json pipe -->
{{prediction | json}}
</div>
最后,您班级中的成员 prediction
必须是类型 Response
prediction!: Response;
所以我认为这应该可行,试试看...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。