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 don’t 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="" />
and finally, extra information that may 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 request AJAX
.
This technique can be useful for the user to have an image preview 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>
<input type="file" id="arquivo" name="arquivo" />
<br />
<img id="imagem" src="#" title="" />
Duplicate of http://answall.com/q/5581/3635
– Guilherme Nascimento
Look at that one example here
– Ivan Ferrer