[英]wcf service call to upload image from angular
我正在尝试通过wcf从有角度的前端上传图像。 它工作正常,我也收到成功消息,但是保存的图像无法在任何其他图像程序的图像查看器中打开。
从stackoverflow先前的答案复制了用于保存接收到的文件流的代码,但是该答案非常旧。
public string PostImage(Stream stream)
{
using (var f = new FileStream(@"C:\Temp\Sample.jpg", FileMode.OpenOrCreate))
{
stream.CopyTo(f);
}
stream.Close();
return "Recieved the image on server";
}
}
如何以正确的格式保存文件。
角文件是
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
fileData: File = null;
constructor(private http: HttpClient) { }
fileProgress(fileInput: any) {
this.fileData = fileInput.target.files[0] as File;
}
onSubmit() {
console.log('Test');
const formData = new FormData();
formData.append('file', this.fileData);
this.http.post('http://localhost:50604/Service1.svc/PostImage', formData, {responseType: 'text'})
.subscribe(res => {
console.log(res);
alert('SUCCESS !!');
});
}
}
看来此服务仅保存139kb文件,并且流中断。 webconfig绑定设置如下
<webHttpBinding>
<binding name="largeMessage" maxReceivedMessageSize="1000000000000" transferMode="Streamed" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:03:00">
<readerQuotas maxStringContentLength="2147483647" maxArrayLength="1000000000" maxBytesPerRead="2147483647" />
<security mode="None"/>
</binding>
</webHttpBinding>
该代码仅将输入流的前10,000个字节复制到C:\\Temp\\Sample.jpg
。 您可能会在以下方面获得更大的成功:
public string PostImage(Stream stream)
{
using (var f = new FileStream(@"C:\Temp\Sample.jpg", FileMode.OpenOrCreate))
{
stream.CopyTo(f);
}
stream.Close();
return "Recieved the image on server";
}
可能是我们的图片未成功保存,例如文件流未完全复制。
我们最好使用异步编程模型上传图像/流。 请参考我的服务接口定义和实现。
IService.cs
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,BodyStyle =WebMessageBodyStyle.Wrapped)]
Task UploadStream(Stream stream);
Service1.svc.cs
public async Task UploadStream(Stream stream)
{
using (stream)
{
//save the image under the Uploads folder on the server-side(root directory).
using (var file = File.Create(Path.Combine(HostingEnvironment.MapPath("~/Uploads"), Guid.NewGuid().ToString() + ".jpg")))
{
await stream.CopyToAsync(file);
}
}
}
随时让我知道问题是否仍然存在。
更新。
WCF内置函数不支持表单数据。 我们应该将流解析为实际的文件内容。
从多部分/表单数据POST读取文件输入
请参考我的示例(MultipartParser类由其他人完成)
Service1.svc.cs
public async Task UploadStream(Stream stream)
{
MultipartParser parser = new MultipartParser(stream);
if (parser.Success)
{
using (var file = File.Create(Path.Combine(HostingEnvironment.MapPath("~/Uploads"), Guid.NewGuid().ToString() + ".png")))
{
await file.WriteAsync(parser.FileContents, 0, parser.FileContents.Length);
}
}
}
对于CORS问题。 请将Global.aspx文件添加到WCF项目。
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With,Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
HTML。
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
<input type="submit" id="mybutton" value="Upload" (click)="onSubmit();">
</div>
App.component.ts
export class AppComponent {
title = 'MyAngular20190808';
fileToUpload: File = null;
constructor(private http: HttpClient) {
}
handleFileInput(file: FileList) {
this.fileToUpload=file.item(0);
}
onSubmit() {
console.log('test');
const formData = new FormData();
formData.append('filekey', this.fileToUpload,this.fileToUpload.name);
this.http.post('http://10.157.18.36:8800/service1.svc/UploadStream', formData, {responseType: 'text' })
.subscribe(res => {
console.log(res);
})
}
}
请随时告诉我是否有什么我可以帮助的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.