First step, to send a file via ajax, you need to disable the default behavior of jQuery ( application/x-www-form-urlencoded
) and use the web standard ( multipart/form-data
).
$.ajax({
url: form.action,
data: data,
contentType: false, // evitar que o jQuery realize o set do 'content-type' para 'application/x-www-form-urlencoded'.
processData: false, // evitar que o jQuery tente serialzar o conteudo usando o $.params().
type: form.method,
success: function(data){
console.log(data);
}
});
Now let's go to the form.:
var form = $("#formUpload")[0];
var enviar = $("#Enviar");
enviar.on("click", function (event) {
var data = new FormData(form);
$.ajax({
url: form.action,
data: data,
contentType: false,
processData: false,
type: form.method,
success: function(data){
console.log(data);
}
});
return false;
});
<form id="formUpload">
<div>
<label>
Descrição:
<input type="text" id="Descricao" name="Descricao" value="" />
</label>
</div>
<div>
<label>
Arquivo
<input type="file" id="Arquivo" name="Arquivo" value="" />
</label>
</div>
<div>
<input type="submit" id="Enviar" name="Enviar" value="Enviar" />
</div>
</form>
Now if you do not have a form and want to upload it as soon as the user selects a file.:
var arquivo = $("#Arquivo");
arquivo.on("change", function (event) {
if (arquivo[0].files.length == 0)
return false;
var data = new FormData();
data.append('Arquivo', arquivo[0].files[0]);
$.ajax({
url: "minha url",
data: data,
contentType: false,
processData: false,
type: "POST",
success: function(data){
console.log(data);
}
});
return false;
});
<input type="file" id="Arquivo" name="Arquivo" value="" />
Finally, extra information that can be useful to you, you can create a link to objects in memory, then you can create a link to the selected image and already update your image without making a AJAX
request.
This technique can be useful for the user to preview the image before uploading.
var arquivo = $("#arquivo");
var imagem = $("#imagem");
arquivo.on("change", function () {
if (arquivo[0].files.length == 0)
return false;
var file = arquivo[0].files[0];
var url = URL.createObjectURL(file);
imagem.attr("src", url);
imagem.attr("title", file.name);
console.log(arquivo[0].files[0]);
});
#imagem {
width: 480px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputtype="file" id="arquivo" name="arquivo" />
<br />
<img id="imagem" src="#" title="" />