Send form with file using ajax web api Entity framework

Asked

Viewed 94 times

0

I’m trying to send a file along with the form to the database, but when I send it returns me error 400 bad request, I don’t understand why.

Curriculoscontroller

    // POST: api/Curriculos
    [ResponseType(typeof(Curriculos))]
    public IHttpActionResult PostCurriculos(Curriculos curriculos)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Curriculos.Add(curriculos);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = curriculos.Id }, curriculos);
    }

Model: Curricula

public partial class Curriculos
{
    public int Id { get; set; }
    public string FileTitle { get; set; }
    public byte[] FileData { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
    public string Fone { get; set; }
    public string Estado { get; set; }
    public string Cidade { get; set; }
    public string Texto { get; set; }
}

Webconfig

public static void Register(HttpConfiguration config)
    {
        // Serviços e configuração da API da Web

        // Rotas da API da Web
        config.MapHttpAttributeRoutes();

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
    }

Form:

<div class="form">
<form method="POST" id="form" class="form" enctype="multipart/form-data" action="http://localhost:59514/api/curriculos">
    <div class="input">
        <i class="fa fa-user" aria-hidden="true"></i> <input type="text" id="nome" class="user" name="nome" placeholder="Nome" required="" />
    </div>
    <div class="input">
        <i class="fa fa-envelope" aria-hidden="true"></i> <input type="email" class="email" name="email" placeholder="Email" required="" />
    </div>
    <div class="input">
        <i class="fa fa-phone" aria-hidden="true"></i> <input type="tel" class="phone" id="fone" name="fone" placeholder="Telefone para contato" required="" />
    </div>
    <div class="input location">
        <i class="fa fa-location-arrow" aria-hidden="true"></i> <input type="text" id="cidade" class="cidade" name="cidade" placeholder="Cidade" required="" />
    </div>
    <div class="input location">
        <i class="fa fa-globe" aria-hidden="true"></i>
        <input type="text" class="estado" id="estado" name="estado" placeholder="Estado" required="" />
    </div>
    <textarea name="texto" id="textarea" rows="3" cols="30" placeholder="Diga-nos, por que quer trabalhar conosco?"></textarea>
    <input id="file" type="file" class="file" name="fileData" />
    <input type="submit" value="Enviar currículo" id="btnPostFile" name="btnPostFile">
</form>
</div>

and the ajax:

$('form.form').on('submit', function() {
    var that = $(this),
        url = that.attr('action'),
        method = that.attr('method'),
        data = {};

    that.find('[name]').each(function(index, value) {
        var that = $(this),
            name = that.attr('name'),
            value = that.val();
        data[name] = value;


    });

    $.ajax({
        url: url,
        type: method,
        data: data,
        success: function(response) {
            console.log(response);
        }
    });


    return false;
})
  • If you’re uploading the file to a Webapi ???

  • The idea is to consume web api for sending the form, and in the form will a file as well...

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.