Skip to content

Instantly share code, notes, and snippets.

@rfcardenas
Last active September 10, 2017 22:32
Show Gist options
  • Save rfcardenas/c523325959243817f691b03367b58203 to your computer and use it in GitHub Desktop.
Save rfcardenas/c523325959243817f691b03367b58203 to your computer and use it in GitHub Desktop.
C#~memory multipart con campos de formulario , utilidad cargar archivos sin guardar en disco y acceder a formdata fields
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace WebApplication3.Controllers
{
public class ValuesController : ApiController
{
// Ejemplo de uso de custom mmultipart provider
[HttpPost, Route("api/image")]
public async Task<IHttpActionResult> Images()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartFormMemoryProvider();
await Request.Content.ReadAsMultipartAsync(provider);
string result = "" + await Request.Content.ReadAsStringAsync();
foreach (var file in provider.Contents)
{
result += file.Headers.ContentDisposition.FileName;
// var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsStringAsync();
//result += buffer;
//Do whatever you want with filename and its binaray data.
}
string data = provider.FormData.GetValues("entidad").FirstOrDefault();
result += data;
return Ok(result);
}
}
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
/**
* Multipart form provider en memoria
* Tratar imagenes en memoria
* Acceder a campos de formData
* */
namespace WebApplication3.Controllers
{
public class MultipartFormMemoryProvider : MultipartMemoryStreamProvider
{
private readonly Collection<bool> _isFormData = new Collection<bool>();
// Coleccion de los campos mapeados
private readonly NameValueCollection _formData = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
public NameValueCollection FormData
{
get { return _formData; }
}
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
if (parent == null) throw new ArgumentNullException("parent");
if (headers == null) throw new ArgumentNullException("headers");
var contentDisposition = headers.ContentDisposition;
if (contentDisposition != null)
{
_isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));
return base.GetStream(parent, headers);
}
throw new InvalidOperationException("Did not find required 'Content-Disposition' header field in MIME multipart body part.");
}
public override async Task ExecutePostProcessingAsync()
{
for (var index = 0; index < Contents.Count; index++)
{
if (IsStream(index))
continue;
var formContent = Contents[index];
var contentDisposition = formContent.Headers.ContentDisposition;
var formFieldName = UnquoteToken(contentDisposition.Name) ?? string.Empty;
var formFieldValue = await formContent.ReadAsStringAsync();
FormData.Add(formFieldName, formFieldValue);
}
}
private static string UnquoteToken(string token)
{
if (string.IsNullOrWhiteSpace(token))
return token;
if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
return token.Substring(1, token.Length - 2);
return token;
}
public bool IsStream(int idx)
{
return !_isFormData[idx];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment