gpt4 book ai didi

java - 在 Angular 8 应用程序中上传媒体文件时如何从 REST API 返回响应?

转载 作者:行者123 更新时间:2023-12-02 09:40:29 25 4
gpt4 key购买 nike

我正在使用以下链接中的文件上传示例: enter link description here

您可以在示例中看到服务器需要返回状态“progress”为了看到进度条。

目前我的其余 api 中有什么:

@POST
@Path("Trip/{tripId}")
@Consumes("multipart/form-data")
@Produces("application/json")
public Response uploadTripVideo(@PathParam("tripId") Integer tripId, MultipartFormDataInput input){

String fileName = "";
Map<String, InputPart> uploadForm = input.getFormData();
InputPart inputPart = uploadForm.get("uploadedFile");
try {

MultivaluedMap<String, String> header = inputPart.getHeaders();
fileName = getFileName(header);

//convert the uploaded file to inputstream
InputStream inputStream = inputPart.getBody(InputStream.class,null);

byte [] bytes = IOUtils.toByteArray(inputStream);
//constructs upload file path
fileName = "C:\\Users\\name\\Documents\\myfolder\\trip\\"+ tripId + "\\video\\" + fileName;
writeFile(bytes,fileName);

} catch (IOException e) {
e.printStackTrace();
}
return Response.status(200)
.entity("uploadFile is called, Uploaded file name : " + fileName).build();
}

这是我的服务电话:

uploadVideo(url: string, file: File): Observable<any> {
let formData = new FormData();
formData.append('uploadedFile', file, file.name);
return this.http.post<any>(this.baseUrl + url, formData, {
reportProgress: true,
observe: 'events'
}).pipe(
map(event => this.getEventMessage(event, formData)),
catchError(this.handleError)
);
}

知道如何返回指示进度的响应吗?问题是调用服务时事件没有到来,这里是我订阅帖子请求的代码:

this.upload.uploadVideo(url, this.videoToUpload)
.subscribe(
(event) => {
console.log(event);
if (event.type === HttpEventType.DownloadProgress) {
console.log("download progress");
}
if (event.type === HttpEventType.Response) {
console.log("donwload completed");
}
this.videoUpload = event;
//console.log("POST call successful value returned in body", val);
},
err => {
this.videoUploadError = err;
//console.log("POST call in error", response);
},
() => {
//console.log("The POST observable is now completed.");
});

我在控制台中得到的是错误:

Backend returned code undefined, body was: undefined

更新我删除了以下代码,事情开始发生变化:

//.pipe(           
// map(event => this.getEventMessage(event, formData)),
// catchError(this.handleError)
// );

最佳答案

您可以通过在 POST HttpRequest 中将 reportProgress 标志设置为 true 来轻松完成此操作。

这里的关键是创建一个 HttpRequest 并将其传递给 HttpClient.request 方法,而不是直接调用 post() 方法.

订阅请求后,您需要检查事件类型

event.type == HttpEventType.UploadProgress

执行逻辑以将加载百分比显示为

100 * event.loaded / event.total

并检查是否完成

event.type === HttpEventType.Response

演示地址:https://stackblitz.com/edit/angular-http-post-status

关于java - 在 Angular 8 应用程序中上传媒体文件时如何从 REST API 返回响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57122901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com