AJAX, PHP 및 jQuery를 사용하여 여러 이미지를 효율적으로 업로드하는 방법은 무엇입니까?
AJAX, PHP, jQuery를 사용하여 여러 이미지를 업로드하는 방법
AJAX, PHP, jQuery를 사용하여 여러 이미지를 업로드하는 것은 웹 개발 시 유용한 기술입니다. 응용 프로그램. 이를 달성하는 데 도움이 되는 문제와 해결 방법을 살펴보겠습니다.
문제:
"AJAX를 사용하여 여러 이미지를 업로드하는 데 문제가 있습니다. 다음은 제가 사용하는 코드입니다. 했어 서면:"
해결책:
여기서 문제는 여러 이미지를 업로드하는 것이 아니라 AJAX를 통해 파일 데이터를 전송하는 데 있습니다. 이 문제를 해결하려면 코드를 수정하고 JSON을 사용하여 파일을 인코딩해야 합니다.
업데이트된 HTML:
<div>
업데이트된 CSS:
#uploads { display: block; position: relative; } #uploads li { list-style: none; } #drop { width: 90%; height: 100px; padding: 0.5em; float: left; margin: 10px; border: 8px dotted grey; } #drop.hover { border: 8px dotted green; } #drop.err { border: 8px dotted orangered; }
업데이트됨 JavaScript:
var display = $('#uploads'); // cache `#uploads`, `this` at `$.ajax()` var droppable = $('#drop')[0]; // cache `#drop` selector $.ajaxSetup({ context: display, contentType: 'application/json', dataType: 'json', beforeSend: function (jqxhr, settings) { // pre-process `file` var file = JSON.parse( decodeURIComponent(settings.data.split(/=/)[1]) ); // add `progress` element for each `file` var progress = $( '<progress />', { class: 'file-' + (!!$('progress').length ? $('progress').length : '0'), min: 0, max: 0, value: 0, 'data-name': file.name, } ); this.append(progress, file.name + '<br />'); jqxhr.name = progress.attr('class'); }, }); var processFiles = function processFiles(event) { event.preventDefault(); // process `input[type=file]`, `droppable` `file` var files = event.target.files || event.dataTransfer.files; var images = $.map(files, function (file, i) { var reader = new FileReader(); var dfd = new $.Deferred(); reader.onload = function (e) { dfd.resolveWith(file, [e.target.result]); }; reader.readAsDataURL(new Blob([file], { type: file.type })); return dfd.then(function (data) { return $.ajax({ type: 'POST', url: '/echo/json/', data: { file: JSON.stringify({ file: data, name: this.name, size: this.size, type: this.type, }), }, xhr: function () { // do `progress` event stuff var uploads = this.context; var progress = this.context.find('progress:last'); var xhrUpload = $.ajaxSettings.xhr(); if (xhrUpload.upload) { xhrUpload.upload.onprogress = function (evt) { progress.attr({ max: evt.total, value: evt.loaded }); }; xhrUpload.upload.onloadend = function (evt) { var progressData = progress.eq(-1); console.log(progressData.data('name') + ' upload complete...'); var img = new Image(); $(img).addClass(progressData.eq(-1).attr('class')); img.onload = function () { if (this.complete) { console.log(progressData.data('name') + ' preview loading...'); } }; uploads.append('<br /><li>', img, '</li><br />'); }; } return xhrUpload; }, }) .then(function (data, textStatus, jqxhr) { console.log(data); this.find('img[class=' + jqxhr.name + ']') .attr('src', data.file) .before( '<span>' + data.name + '</span><br />' ); return data; }, function (jqxhr, textStatus, errorThrown) { console.log(errorThrown); return errorThrown; }); }); }); $.when.apply(display, images).then(function () { var result = $.makeArray(arguments); console.log(result.length, 'uploads complete'); }, function err(jqxhr, textStatus, errorThrown) { console.log(jqxhr, textStatus, errorThrown); }); }; $(document).on('change', 'input[name^=file]', processFiles); // process `droppable` events droppable.ondragover = function () { $(this).addClass('hover'); return false; }; droppable.ondragend = function () { $(this).removeClass('hover'); return false; }; droppable.ondrop = function (e) { $(this).removeClass('hover'); var image = Array.prototype.slice.call(e.dataTransfer.files) .every(function (img, i) { return /^image/.test(img.type); }); e.preventDefault(); // if `file`, file type `image` , process `file` if (!!e.dataTransfer.files.length && image) { $(this).find('.drop-area-label').css('color', 'blue').html(function (i, html) { $(this).delay(3000, 'msg').queue('msg', function () { $(this).css('color', 'initial').html(html); }).dequeue('msg'); return 'File dropped, processing file upload...'; }); processFiles(e); } else { // if dropped `file` _not_ `image` $(this).removeClass('hover').addClass('err').find('.drop-area-label').css('color', 'darkred').html(function (i, html) { $(this).delay(3000, 'msg').queue('msg', function () { $(this).css('color', 'initial').html(html) .parent('#drop').removeClass('err'); }).dequeue('msg'); return 'Please drop image file...'; }); }; };
업데이트된 PHP:
<?php if (isset($_POST['file'])) { // do php stuff // call `json_encode` on `file` object $file = json_encode($_POST['file']); // return `file` as `json` string echo $file; }
이 수정된 코드를 구현하면 AJAX, PHP 및 jQuery.
위 내용은 AJAX, PHP 및 jQuery를 사용하여 여러 이미지를 효율적으로 업로드하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











기사는 JavaScript 라이브러리 작성, 게시 및 유지 관리, 계획, 개발, 테스트, 문서 및 홍보 전략에 중점을 둡니다.

이 기사는 브라우저에서 JavaScript 성능을 최적화하기위한 전략에 대해 설명하고 실행 시간을 줄이고 페이지로드 속도에 미치는 영향을 최소화하는 데 중점을 둡니다.

프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

이 기사는 브라우저 개발자 도구를 사용하여 효과적인 JavaScript 디버깅, 중단 점 설정, 콘솔 사용 및 성능 분석에 중점을 둡니다.

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

이 기사는 소스 맵을 사용하여 원래 코드에 다시 매핑하여 미니어링 된 JavaScript를 디버그하는 방법을 설명합니다. 소스 맵 활성화, 브레이크 포인트 설정 및 Chrome Devtools 및 Webpack과 같은 도구 사용에 대해 설명합니다.

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

Console.log 출력의 차이의 근본 원인에 대한 심층적 인 논의. 이 기사에서는 Console.log 함수의 출력 결과의 차이점을 코드에서 분석하고 그에 따른 이유를 설명합니다. � ...
