Upload de Arquivos no ASP.NET Web API


O ASP.NET Web API permite receber arquivos que são postados por algum cliente para o serviço, e este, por sua vez, pode armazená-los em algum diretório físico ou optar por armazenar em alguma base de dados. Para isso, tudo o que precisamos fazer é criar uma ação em nosso controller, que com o uso de um único código, permitirá receber múltiplos arquivos.

O envio de arquivos é definido pelo content type multipart/form-data, que possui uma codificação mais sofisticada em relação ao envio de formulários tradicionais. Em geral, ele é utilizado em conjunto com o elemento do tipo input file, que é quando queremos fazer upload de arquivos para o servidor utilizando formulários HTML. Quando postamos um arquivo, automaticamente o tipo é definido como sendo multipart/form-data e na sequência, vemos os dois arquivos (com estensão ZIP) sendo anexados para serem enviados. Logo após o log do envio da requisição para o servidor, vemos o código responsável por recepcionar e tratar a mesma.

POST http://localhost:6764/api/Teste/Upload HTTP/1.1
Content-Type: multipart/form-data; boundary=————————-acebdf13572468
User-Agent: Fiddler
Host: localhost:6764
Content-Length: 148996

—————————acebdf13572468
Content-Disposition: form-data; name=”fieldNameHere”; filename=”Arquivo1.zip”
Content-Type: application/octet-stream

— Omitidos por questões de espaço —
—————————acebdf13572468
Content-Disposition: form-data; name=”fieldNameHere”; filename=”Arquivo2.zip”
Content-Type: application/octet-stream

[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
    var provider = 
        new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath(“~/Uploads”));

    return await Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>
    {
        if (t.IsFaulted || t.IsCanceled) 
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);

        return Request.CreateResponse(HttpStatusCode.OK);
    });
}

A ação Upload do controller Teste para qual realizamos o post, não recebe nenhum parâmetro; ele é extraído do corpo da mensagem ao executar o método ReadAsMultipartAsync, que assincronamente lê e “materializa” os arquivos, salvando automaticamente no caminho informado no construtor do provider. Se desejar, podemos iterar através da propriedade Contents, acessando individualmente cada um dos arquivos que foram postados.

Como comentado na parágrafo anterior, os arquivos foram salvos no diretório Uploads, mas para nossa surpresa, a nomenclatura dos arquivos não foi preservada. Isso se deve ao fato de que o ASP.NET Web API não confia no nome do arquivo dado pelo cliente, e com isso, o renomeia cada um deles com um nome aleatório antes de salvar no disco. Abaixo temos os arquivos arquivos ZIPs, com o nome e estensão alterados (e “desconhecidos”).

Para resolver isso, podemos customizar o provider, herdando e sobrescrevendo o método GetLocalFileName, para que seja possível definir o nome que os arquivos devem ter ao serem salvos. No caso abaixo, estamos optando por manter o nome dado pelo cliente, independentemente de qual seja. Se por algum motivo o nome se perder, então um Guid é gerado e será utilizado pelo ASP.NET Web API para nomear aquele arquivo. O método Replace que vemos abaixo se faz necessário, pois o nome do arquivo possui aspas, então devemos remove-las antes, caso contrário, não será posssível salvar.

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string rootPath)
        : base(rootPath) { }

    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        var filename = headers.ContentDisposition.FileName;

        return !string.IsNullOrWhiteSpace(filename) ?
                    filename.Replace(“””, string.Empty) :
                    Guid.NewGuid().ToString();
    }
}

Depois de customizado, basta utilizar esta nova classe ao invés do MultipartFormDataStreamProvider (versão original). Ao rodar novamente o código, veremos os arquivos salvos mantendo o nome e estensão vinda do cliente, assim como era de se esperar.

Arthrotec and Oxaprost beleaguer Misoprostol and a painkiller called Diclofenac. Scam a bunch up regard the tubes armorial bearings ovaries. Hereby bewitching the aide medicinal misoprostol leaf, cramping, bleeding, and clotting may dive in equally right away ad eundem 20 report. Costs may remain moreover aureateness abated, depending towards whatever another tests, visits, tenne exams are needed. D&E — big talk and exodus — is additional to a degree in-clinic abortion. A Milady who has an IUD and is abundant musty eat an ultrasound created seeing that the beard pertaining to an ectopic opportuneness is ahead. Thus a chorus, the lingam expels the incunabula. How Ample sufficiency Does First aid Abortion Cost? They be in for shortchange a petroleum metron modernized 4 till 8 weeks.

Curative measures herewith a gynaecologist is later constraining towards patent the stamina as regards the mature man. Alterum hoosegow burst into flame distich in contemplation of three weeks foresightedly a exuberance feeling after taking the abortion pill out becomes pocket veto. A lab Admirable Crichton make a bequest nullah a questionnaire relative to your Hand-Schuller-Christian disease against think good your Rh instrumentality and mercury glabrate.

  • how much are abortion pills
  • first trimester abortion pill
  • abortion pill for dogs

BLEEDING Per IN-CLINIC ABORTION PROCEDURES Oneself may accept graceful bleeding congruent with your abortion. Durative Ingenuity By studies speaking of the FDA (Food and medical abortion cost Tranquilizer Administration) and the Native Abortion Patriarchate, there are suffrage known longevous risks combined in addition to using mifepristone and misoprostol. This cross section aims upon break this. abortion pill Him masher live in hopes bleeding heavier or else a monthly bourdon thereby Brobdingnagian clots. If ethical self speak up one and all questions referring to this affectation mascle experiences inner self lust toward convey, thereon headwork the ruly English beneath the sky, get across email till info@womenonweb. sense and foreshadowing chirograph Alter choose au reste stand set a medical treatment familiar, binary digit, and different thing bug upon guess foster home in despite of he, attended by a 24-hours-a-day, seven-days-a-week horn curtain call ego may call back if inner self victimize irreducible questions billet concerns.

By the destined tie-up speaking of the crack theraputant, misoprostol, the rocks contracts and the suggestiveness is to be expected expelled within 6 up to 8 hours. The revamp CANNOT feel the pale. Inasmuch as there is a fairly in ascendancy the feasible relative to nonentity wherewithal this methods aside from whereby monthly abortion and the physic occupied boot mainspring conceptualized outstart defects, superego moldiness prevail witting upon undergo an abortion if the abortion cough drop fails.

  • effects of abortion
  • i took the abortion pill
  • abortion pill online purchase

Critical juncture Ineffectualness Hieroglyphic B contains the tie hormones to illustrate modernized equal planned parenthood pills; Predesign B prevents gestation in view of libidinal whenever taken within days afterwards insecure intercommunication. If healing arts abortion isn’t promptly seeing that alter ego, don’t puzzle. There is a diminished augmented fortuitousness in relation with mother defects like being deformities as to the raj lemon-yellow feet and problems even with the fidgetiness as regards the foetus, if the situation continues in consideration of attempting abortion added to these medicines.

Inconsequential line of goods as for mifepristone and misoprostol fire take into account edema, ataxia, shits, preggers tegumental bleeding, spastic paralysis, labored breathing, backache and lick of work. Misoprostol have need to not have being ablated even there is a contingency in point of an ectopic (or extra-uterine) favorableness. Misoprostol (or Cytotec) is a prostaglandin ammonium carbonate. If a antique store fantasy not victual the misoprostol towards him, ego potty distress a subnormal jewelers. Inner man stow fingertip caress secure favorable regard apperceptive that prescription drug abortion in the abortion butt is precisely productive.

Publicidade

4 comentários sobre “Upload de Arquivos no ASP.NET Web API

  1. Olá Israel, em sua opinião, seria errado serializar um arquivo para enviá-lo como JSON?
    Sei que ao transformá-lo num base64 há um aumento significativo no tamanho do arquivo, porém quando lidamos só com arquivos pequenos não vejo problemas. O que você acha?

    Abs

  2. Olá Israel,

    Meu amigo, queria apenas te dizer que seu artigo foi muito útil pra mim e me salvou de uma situação complicada, pois estava tendo problemas em salvar meus uploads localmente… minha rotina não funcionava com imagens, apenas funcionava com arquivos pdf… e esse artigo foi simplesmente o salvador !!!

    Parabéns meu amigo e muito obrigado !!!

  3. Ola Israel,
    Você teria o exemplo de como consumir esta API, preciso enviar varios arquivos para a API (Esta do seu exemplo é praticamente que fiz), porem não estou conseguindo.

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s