我尝试使用WCF使用表单数据上传图像。我正在编写下面的代码来获取WCF代码中的图像,但它始终向我发送 null 值,但我能够以字节接收图像流即可。我的主要目标是使用原始图像元数据保存图像。
HttpPostedFile file = HttpContext.Current.Request.Files["media1"];
要完成此功能,我已添加:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
在 Web.Config :
中 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
注意:我想用元数据保存图片。
答案 0 :(得分:0)
您不应使用HttpContext
来获取WCF中的文件。您可以简单地创建一个以流作为输入的服务。这里有一个简单的例子:Uploading an image using WCF RESTFul service full working example
<强>更新强>
尝试字节数组而不是流,并像这样包装类:
public class Input
{
[DataMember]
public string fileName { get; set; }
[DataMember]
public DateTime createdDate{ get; set; }
[DataMember]
public DateTime modifiedDate{ get; set; }
[DataMember]
public byte[] fileContents { get; set; }
.
.
}
然后简单地将文件写在磁盘上或任何你想要的地方:
public string Upload(Input input)
{
File.WriteAllBytes(input.fileName, input.fileContents);
return "OK";
}
答案 1 :(得分:0)
最后,在给定link
的帮助下解决了我的问题我在我的实现中编写了下面的代码,我刚从codeplex下载了 MultipartParser.cs 类,而且我在这里粘贴了完整的类,因为 Codeplex 在一些之后会下降时间。
public string Upload(Stream data)
{
MultipartParser parser = new MultipartParser(data);
if (parser.Success)
{
// Save the file
string filename = parser.Filename;
string contentType = parser.ContentType;
byte[] filecontent = parser.FileContents;
File.WriteAllBytes(@"C:\test1.jpg", filecontent);
}
return "OK";
}
MultipartParser.cs类:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
/// <summary>
/// MultipartParser http://multipartparser.codeplex.com
/// Reads a multipart form data stream and returns the filename, content type and contents as a stream.
/// 2009 Anthony Super http://antscode.blogspot.com
/// </summary>
namespace WcfService1
{
public class MultipartParser
{
public MultipartParser(Stream stream)
{
this.Parse(stream, Encoding.UTF8);
}
public MultipartParser(Stream stream, Encoding encoding)
{
this.Parse(stream, encoding);
}
public static async Task ParseFiles(Stream data, string contentType, Action<string, Stream> fileProcessor)
{
var streamContent = new StreamContent(data);
streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
var provider = await streamContent.ReadAsMultipartAsync();
foreach (var httpContent in provider.Contents)
{
var fileName = httpContent.Headers.ContentDisposition.FileName;
if (string.IsNullOrWhiteSpace(fileName))
{
continue;
}
using (Stream fileContents = await httpContent.ReadAsStreamAsync())
{
fileProcessor(fileName, fileContents);
}
}
}
private void Parse(Stream stream, Encoding encoding)
{
this.Success = false;
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1)
{
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
// Look for Content-Type
Regex re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = re.Match(content);
// Look for filename
re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success)
{
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
// Get the start & end indexes of the file contents
int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
int endIndex = IndexOf(data, delimiterBytes, startIndex);
int contentLength = endIndex - startIndex;
// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true;
}
}
}
private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)
{
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1)
{
while ((startPos + index) < searchWithin.Length)
{
if (searchWithin[startPos + index] == serachFor[index])
{
index++;
if (index == serachFor.Length)
{
return startPos;
}
}
else
{
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1)
{
return -1;
}
index = 0;
}
}
}
return -1;
}
private byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success
{
get;
private set;
}
public string ContentType
{
get;
private set;
}
public string Filename
{
get;
private set;
}
public byte[] FileContents
{
get;
private set;
}
}
}