63 lines
2.1 KiB
C#
63 lines
2.1 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using System.Web;
|
|
using System.Web.Http;
|
|
|
|
namespace Thermo.Active.Provider
|
|
{
|
|
public class FileResult : IHttpActionResult
|
|
{
|
|
private readonly string FilePath;
|
|
private readonly string ContentType;
|
|
private readonly string FileName;
|
|
|
|
public FileResult(string filePath, string contentType = null, string fileName = null)
|
|
{
|
|
FilePath = filePath;
|
|
ContentType = contentType;
|
|
FileName = fileName;
|
|
}
|
|
|
|
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
|
|
{
|
|
return Task.Run(() =>
|
|
{
|
|
// Create response
|
|
var response = new HttpResponseMessage(HttpStatusCode.OK)
|
|
{
|
|
Content = new StreamContent(File.OpenRead(FilePath)) // Set file
|
|
};
|
|
// Set header content type
|
|
var contentType = ContentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(FilePath));
|
|
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
|
|
|
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
|
|
{
|
|
FileName = FileName
|
|
};
|
|
|
|
return response;
|
|
}, cancellationToken);
|
|
}
|
|
}
|
|
|
|
// Override MultipartFormDataStreamProvider to override the GetLocalFileName
|
|
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
|
|
{
|
|
public CustomMultipartFormDataStreamProvider(string path) : base(path)
|
|
{
|
|
}
|
|
|
|
public override string GetLocalFileName(HttpContentHeaders headers)
|
|
{
|
|
var fileName = headers.ContentDisposition.FileName.Replace("\"", string.Empty);
|
|
|
|
return Path.GetFileNameWithoutExtension(fileName) + Guid.NewGuid() + Path.GetExtension(fileName);
|
|
}
|
|
}
|
|
} |