[英]HttpContext.Current.Request.Files Always Null in WCF [save image with original metadata]
我正在嘗試使用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" />
注意 : 我想用元數據保存圖像 。
您不應該使用HttpContext
來獲取WCF中的文件。 您可以簡單地創建一個以流作為輸入的服務。 這里有一個簡單的例子: 使用WCF RESTFul服務完整工作示例上傳圖像
更新:
嘗試字節數組而不是流並包裝類如下:
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";
}
最后,我的問題在給定鏈接的幫助下解決了
我在我的實現中編寫了下面的代碼,我剛從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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.