wcf服务呼叫以从角度上传图像
我正在尝试从有角度的前端通过wcf上传图像.它工作正常,我也收到一条成功消息,但是保存的图像无法在任何其他图像程序的图像查看器中打开.
I am trying to upload an image through wcf from angular frontend. It is working fine and I am receiving a success message too but the image saved is not opening in image viewer of any other image program.
用于保存接收到的文件流的代码是从stackoverflow先前的答案中复制的,但是该答案非常旧.
the code to save the received file stream is copied from stackoverflow previous answer but that answer was very old.
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";
}
}
如何以正确的格式保存文件.
How can I save the file in correct format.
角度文件是
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绑定设置如下
It appears that this service is saving only 139kb file and stream is breaking. The webconfig binding settings are as follows
<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>
可能是我们的图像未成功保存,例如文件流未完全复制.
我们最好使用异步编程模型上传图像/流.请参考我的服务接口定义和实现.
IService.cs
It may be that our image was not saved successfully, such as the file stream is not completely copied.
We had better upload the image/stream by using Asynchronous programming model. Please refer to my service interface definition and implementation.
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);
}
}
}
请随时让我知道问题是否仍然存在.
Feel free to let me know if the problem still exists.
已更新.
WCF内置功能不支持表单数据.
我们应该将流解析为实际的文件内容.
从multipart/form-data POST读取文件输入
请参考我的示例(MultipartParser类由其他人完成)
Service1.svc.cs
Updated.
Form Data is not supported by WCF built-in function.
We should parse the stream to the practical file content.
Reading file input from a multipart/form-data POST
Please refer to my example (MultipartParser class is completed by others)
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);
})
}
}
请随时告诉我是否有什么可以帮忙的.
Feel free to let me know if there is anything I can help with.
已更新.