7
A
回答
7
以下回答详细使用一些技术将二进制数据发布到宁静的服务。
- Post binary data to a RESTful application
- What is a good way to transfer binary data to a HTTP REST API service?
- Bad idea to transfer large payload using web services?
下面的代码是你如何可以写一个RESTful的WCF服务的样本,是不完整,但不给你在哪里指示你可以开始。
样品服务,请注意,这是不是生产就绪代码。
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class FileService
{
private IncomingWebRequestContext m_Request;
private OutgoingWebResponseContext m_Response;
[WebGet(UriTemplate = "{appName}/{id}?action={action}")]
public Stream GetFile(string appName, string id, string action)
{
var repository = new FileRepository();
var response = WebOperationContext.Current.OutgoingResponse;
var result = repository.GetById(int.Parse(id));
if (action != null && action.Equals("download", StringComparison.InvariantCultureIgnoreCase))
{
response.Headers.Add("Content-Disposition", string.Format("attachment; filename={0}", result.Name));
}
response.Headers.Add(HttpResponseHeader.ContentType, result.ContentType);
response.Headers.Add("X-Filename", result.Name);
return result.Content;
}
[WebInvoke(UriTemplate = "{appName}", Method = "POST")]
public void Save(string appName, Stream fileContent)
{
try
{
if (WebOperationContext.Current == null) throw new InvalidOperationException("WebOperationContext is null.");
m_Request = WebOperationContext.Current.IncomingRequest;
m_Response = WebOperationContext.Current.OutgoingResponse;
var file = CreateFileResource(fileContent, appName);
if (!FileIsValid(file)) throw new WebFaultException(HttpStatusCode.BadRequest);
SaveFile(file);
SetStatusAsCreated(file);
}
catch (Exception ex)
{
if (ex.GetType() == typeof(WebFaultException)) throw;
if (ex.GetType().IsGenericType && ex.GetType().GetGenericTypeDefinition() == typeof(WebFaultException<>)) throw;
throw new WebFaultException<string>("An unexpected error occurred.", HttpStatusCode.InternalServerError);
}
}
private FileResource CreateFileResource(Stream fileContent, string appName)
{
var result = new FileResource();
fileContent.CopyTo(result.Content);
result.ApplicationName = appName;
result.Name = m_Request.Headers["X-Filename"];
result.Location = @"C:\SomeFolder\" + result.Name;
result.ContentType = m_Request.Headers[HttpRequestHeader.ContentType] ?? this.GetContentType(result.Name);
result.DateUploaded = DateTime.Now;
return result;
}
private string GetContentType(string filename)
{
// this should be replaced with some form of logic to determine the correct file content type (I.E., use registry, extension, xml file, etc.,)
return "application/octet-stream";
}
private bool FileIsValid(FileResource file)
{
var validator = new FileResourceValidator();
var clientHash = m_Request.Headers[HttpRequestHeader.ContentMd5];
return validator.IsValid(file, clientHash);
}
private void SaveFile(FileResource file)
{
// This will persist the meta data about the file to a database (I.E., size, filename, file location, etc)
new FileRepository().AddFile(file);
}
private void SetStatusAsCreated(FileResource file)
{
var location = new Uri(m_Request.UriTemplateMatch.RequestUri.AbsoluteUri + "/" + file.Id);
m_Response.SetStatusAsCreated(location);
}
}
样品客户,注意,这是不生产准备代码。
// *********************************
// Sample Client
// *********************************
private void UploadButton_Click(object sender, EventArgs e)
{
var uri = "http://dev-fileservice/SampleApplication"
var fullFilename = @"C:\somefile.txt";
var fileContent = File.ReadAllBytes(fullFilename);
using (var webClient = new WebClient())
{
try
{
webClient.Proxy = null;
webClient.Headers.Add(HttpRequestHeader.ContentMd5, this.CalculateFileHash());
webClient.Headers.Add("X-DaysToKeep", DurationNumericUpDown.Value.ToString());
webClient.Headers.Add("X-Filename", Path.GetFileName(fullFilename));
webClient.UploadData(uri, "POST", fileContent);
var fileUri = webClient.ResponseHeaders[HttpResponseHeader.Location];
Console.WriteLine("File can be downloaded at" + fileUri);
}
catch (Exception ex)
{
var exception = ex.Message;
}
}
}
private string CalculateFileHash()
{
var hash = MD5.Create().ComputeHash(File.ReadAllBytes(@"C:\somefile.txt"));
var sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("x2"));
}
return sb.ToString();
}
private void DownloadFile()
{
var uri = "http://dev-fileservice/SampleApplication/1" // this is the URL returned by the Restful file service
using (var webClient = new WebClient())
{
try
{
webClient.Proxy = null;
var fileContent = webClient.DownloadData(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
相关问题
- 1. 从WCF服务流式传输文件
- 2. 从Sharepoint WCF流式传输
- 3. 通过HTTP通过WCF流式传输文件上传IOException
- 4. 使用WCF流式传输上传文件,从流式传输中读取微小的文件
- 5. WCF流媒体文件传输
- 6. 流式传输wav文件
- 7. 流式传输MP4文件
- 8. WCF流式传输/分块上传?
- 9. 文件传输/ WCF
- 10. 通过WCF流式传输100个文件?
- 11. WCF文件流式传输400错误请求
- 12. 如何在流式传输结束后删除文件wcf
- 13. Silverlight + WCF。流式传输音频和视频文件
- 14. WCF传递文件流
- 15. 何时使用WCF流式传输
- 16. 使用NetTcpBinding通过WCF流式传输
- 17. WCF和流式传输大数据
- 18. WCF REST - 与IIS6流式传输问题
- 19. 使用WCF流式传输限制
- 20. 支持的WCF流式传输绑定
- 21. 使用WCF流式传输数据
- 22. .NET - 将DataSet(XML数据)流式传输到ZIP文件?
- 23. 我想使用C#从XML文件流式传输数据.net
- 24. 在.NET中,将数据从SQL流式传输到文件
- 25. 流式传输大型视频文件.net
- 26. 如何使用SQL文件流式传输win32 API并支持WCF流式传输
- 27. 传输文件流
- 28. .NET中的Hadoop流式传输
- 29. 在.Net中进行HTTP流式传输
- 30. 上传文件MVC 4 Web API .NET 4
什么是流媒体?您是否尝试将WCF用于媒体内容(I.E.,视频或MP3),还是将二进制信息发送回客户端? – Kane
基本上我试图通过http上传文件到我的服务器。 – tugberk