Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <form id="formulario" method="post" enctype="multipart/form-data">
- <input type="text" name="campo1" value="hello" />
- <input type="text" name="campo2" value="world" />
- <input name="arquivo" type="file" />
- <button>Enviar</button>
- </form>
- $("#formulario").submit(function() {
- var formData = new FormData(this);
- $.ajax({
- url: window.location.pathname,
- type: 'POST',
- data: formData,
- success: function(data) {
- alert(data)
- },
- cache: false,
- contentType: false,
- processData: false,
- xhr: function() { // Custom XMLHttpRequest
- var myXhr = $.ajaxSettings.xhr();
- if (myXhr.upload) { // Avalia se tem suporte a propriedade upload
- myXhr.upload.addEventListener('progress', function() {
- /* faz alguma coisa durante o progresso do upload */
- }, false);
- }
- return myXhr;
- }
- });
- });
- <input type="file" id="fileUpload" name="fileUpload" />
- <input type="button" id="btnEnviar" value="Enviar" />
- $(function () {
- var form;
- $('#fileUpload').change(function (event) {
- form = new FormData();
- form.append('fileUpload', event.target.files[0]); // para apenas 1 arquivo
- //var name = event.target.files[0].content.name; // para capturar o nome do arquivo com sua extenção
- });
- $('#btnEnviar').click(function () {
- $.ajax({
- url: 'URL SERVER', // Url do lado server que vai receber o arquivo
- data: form,
- processData: false,
- contentType: false,
- type: 'POST',
- success: function (data) {
- // utilizar o retorno
- }
- });
- });
- });
- $(form).on('submit', function () {
- var data;
- var contentType = "application/x-www-form-urlencoded";
- var processData = true;
- if ($(this).attr('enctype') == 'multipart/form-data') {
- data = new FormData($('.form-horizontal').get(0));//seleciona classe form-horizontal adicionada na tag form do html
- contentType = false;
- processData = false;
- } else {
- data = $(this).serialize();
- }
- $.ajax({
- data: data,
- type: $(this).attr('method'),
- url: $(this).attr('action'),
- contentType: contentType,
- processData: processData,
- success: function (response) {
- //seu código após sucesso
- },
- error: function (exr, sender) {
- alert('Erro ao carregar pagina');
- }
- });
- }
- <input type="file" id="uploadArquivos" multiple>
- var uploadArquivo = $("#uploadArquivos");
- uploadArquivo.on('change', function(e) {
- files = e.target.files;
- var formData = new FormData(),
- file = [];
- $.each(files, function(key, val) {
- file[key] = val;
- });
- formData.append('file', file);
- $.ajax({
- url: 'urlDoArquivo',
- cache: false,
- contentType: false,
- processData: false,
- data: formData,
- type: 'post',
- success: function(data) {
- }
- });
- });
- foreach ($_FILES as $value):
- move_uploaded_file($value['tmp_name'], '../temp/' . $value['name']);
- endforeach;
Add Comment
Please, Sign In to add comment