Может кто-нибудь объяснить, как реализовать плагин загрузки файла jQuery?
ОБНОВЛЕНИЕ (октябрь 2019 г.):
6 лет спустя, и загрузка файлов jQuery явно все еще сводит людей с ума. Если вы находите здесь немного утешения в ответах, попробуйте
поиск NPM для современной альтернативы. Это не стоит хлопот, я обещаю.
Я рекомендовал Uploadify в предыдущем редактировании, но, как отметил комментатор, они больше не предлагают бесплатную версию. Так или иначе, Uploadify был 2013 годом.
ОБНОВЛЕНИЕ:
Это все еще похоже на трафик, поэтому я объясню, что я в итоге сделал. В итоге я получил плагин, следуя инструкции в принятом ответе. Тем не менее, jQuery File Upload - это настоящая проблема, и если вы ищете более простой плагин для загрузки файлов, я настоятельно рекомендую
Uploadify. Как указывалось в ответе, оно бесплатно только для некоммерческого использования.
Фон
Я пытаюсь использовать blueimp jQuery File Upload, чтобы позволить пользователям загружать файлы. Из коробки он работает отлично, следуя инструкциям по установке. Но чтобы использовать его практически на моем веб-сайте, я хочу сделать пару вещей:
- Включить загрузчик на любую из моих существующих страниц
- Изменить каталог для загружаемых файлов
Все файлы для плагина находятся в папке под корнем.
Я пытался...
- Перемещение демонстрационной страницы в корень и обновление путей для необходимых скриптов
- Изменение параметров "upload_dir" и "upload_url" в файле UploadHandler.php, как указано здесь.
- Изменение URL во второй строке демонстрационного javascript
Во всех случаях отображается предварительный просмотр и запускается индикатор выполнения, но файлы не загружаются, и я получаю эту ошибку в консоли: Uncaught TypeError: Cannot read property 'files' of undefined
. Я не понимаю, как работают все части плагина, что затрудняет его отладку.
Код
JavaScript на демонстрационной странице:
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = 'file_upload/server/php/UploadHandler.php',
uploadButton = $('<button/>')
.addClass('btn')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#fileupload').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append(file.error);
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
});
}).on('fileuploadfail', function (e, data) {
$.each(data.result.files, function (index, file) {
var error = $('<span/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Я удивлен отсутствием документации; кажется, что это должно быть просто изменить. Буду признателен, если кто-нибудь сможет объяснить, как это сделать.
Ответы
Ответ 1
Я искал аналогичную функциональность несколько дней назад и наткнулся на хороший учебник по tutorialzine. Вот рабочий пример. Полный учебник можно найти здесь.
Простая форма для хранения диалога загрузки файлов:
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="uploadctl" multiple />
<ul id="fileList">
<!-- The file list will be shown here -->
</ul>
</form>
И вот код jQuery для загрузки файлов:
$('#upload').fileupload({
// This function is called when a file is added to the queue
add: function (e, data) {
//This area will contain file list and progress information.
var tpl = $('<li class="working">'+
'<input type="text" value="0" data-width="48" data-height="48" data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />'+
'<p></p><span></span></li>' );
// Append the file name and file size
tpl.find('p').text(data.files[0].name)
.append('<i>' + formatFileSize(data.files[0].size) + '</i>');
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin. This part can be ignored, if you are showing progress in some other way.
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function(){
if(tpl.hasClass('working')){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
progress: function(e, data){
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if(progress == 100){
data.context.removeClass('working');
}
}
});
//Helper function for calculation of progress
function formatFileSize(bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
}
И вот пример кода PHP для обработки данных:
if($_POST) {
$allowed = array('jpg', 'jpeg');
if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){
$extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], "/yourpath/." . $extension)){
echo '{"status":"success"}';
exit;
}
echo '{"status":"error"}';
}
exit();
}
Вышеприведенный код может быть добавлен в любую существующую форму. Эта программа автоматически загружает изображения после их добавления. Эта функция может быть изменена, и вы можете отправить изображение, пока вы отправляете свою существующую форму.
Обновлен мой ответ с фактическим кодом. Все кредиты оригинальному автору кода.
Источник:
http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/
Ответ 2
Я только что провел 2 часа, сражаясь с загрузкой jQuery, но сдался из-за количества зависимостей (у меня было 13 JS файлов, включенных, чтобы получить все колокола и свистки).
Я немного поработал и наткнулся на опрятный проект Dropzone.js, который не имеет никаких зависимостей.
Автор также создал демонстрацию bootstrap, которая была вдохновлена плагином загрузки файлов jQuery.
Надеюсь, это немного сэкономит время.
Ответ 3
Я также боролся с этим, но получил его работу, как только я понял, как пути работают в UploadHandler.php: upload_dir и upload_url, - это единственные настройки, на которые можно посмотреть, чтобы заставить его работать. Также проверяйте свои журналы ошибок сервера для отладки информации.
Ответ 4
Завершите загрузку изображения с помощью предварительного просмотра изображения с помощью плагина jQuery.
HTML
<div class="target" width="78" height="100"><img /></div>
JS
$(".target").dropper({
action: "upload.php",
}).on("start.dropper", onStart);
function onStart(e, files){
console.log(files[0]);
image_preview(files[0].file).then(function(res){
$('.dropper-dropzone').empty();
//$('.dropper-dropzone').css("background-image",res.data);
$('#imgPreview').remove();
$('.dropper-dropzone').append('<img id="imgPreview"/><span style="display:none">Drag and drop files or click to select</span>');
var widthImg=$('.dropper-dropzone').attr('width');
$('#imgPreview').attr({width:widthImg});
$('#imgPreview').attr({src:res.data});
})
}
function image_preview(file){
var def = new $.Deferred();
var imgURL = '';
if (file.type.match('image.*')) {
//create object url support
var URL = window.URL || window.webkitURL;
if (URL !== undefined) {
imgURL = URL.createObjectURL(file);
URL.revokeObjectURL(file);
def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
}
//file reader support
else if(window.File && window.FileReader)
{
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function () {
imgURL = reader.result;
def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
}
}
else {
def.reject({status: 1001, message: 'File uploader not supported', data:imgURL, error: {}});
}
}
else
def.reject({status: 1002, message: 'File type not supported', error: {}});
return def.promise();
}
$('.dropper-dropzone').mouseenter(function() {
$( '.dropper-dropzone>span' ).css("display", "block");
});
$('.dropper-dropzone').mouseleave(function() {
$( '.dropper-dropzone>span' ).css("display", "none");
});
CSS
.dropper-dropzone{
width:78px;
padding:3px;
height:100px;
position: relative;
}
.dropper-dropzone>img{
width:78px;
height:100px;
margin-top=0;
}
.dropper-dropzone>span {
position: absolute;
right: 10px;
top: 20px;
color:#ccc;
}
.dropper .dropper-dropzone{
padding:3px !important
}
Демо Jsfiddle
Ответ 5
Это хороший Angular плагин для загрузки файлов и его бесплатный!
angular загрузка файла
Ответ 6
Я некоторое время боролся с этим плагином на Rails, а затем кто-то подсказал, что он переустанавливает весь код, который я создал.
Хотя похоже, что вы не используете это в Rails, однако, если кто-то использует его, посмотрите gem. Источник здесь → jQueryFileUpload Rails.
Обновление:
Чтобы удовлетворить комментатора, я обновил свой ответ. По существу " использовать этот камень, вот исходный код" Если он исчезнет, сделайте это долгий путь.
Ответ 7
Привет попробуйте ниже ссылку это очень легко. Я застрял в течение долгого времени, и это решило мою проблему за несколько минут.http://simpleupload.michaelcbrook.com/#examples
Ответ 8
Droply.js идеально подходит для этого. Это просто и поставляется в комплекте с демонстрационным сайтом, который работает из коробки.
Ответ 9
Вы можете использовать uploadify
это лучший плагин jupery multiupload, который я использовал.
Реализация прост, поддержка браузера прекрасна.
Ответ 10
Для плагина пользовательского интерфейса, с страницей jsp и Spring MVC..
Пример html. Необходимо находиться в элементе формы с атрибутом id fileupload
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="fileupload-buttonbar">
<div>
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files</span>
<input id="fileuploadInput" type="file" name="files[]" multiple>
</span>
<%-- https://stackoverflow.com/info/925334/how-is-the-default-submit-button-on-an-html-form-determined --%>
<button type="button" class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel upload</span>
</button>
<!-- The global file processing state -->
<span class="fileupload-process"></span>
</div>
<!-- The global progress state -->
<div class="fileupload-progress fade">
<!-- The global progress bar -->
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-success" style="width:0%;"></div>
</div>
<!-- The extended global progress state -->
<div class="progress-extended"> </div>
</div>
</div>
<!-- The table listing the files available for upload/download -->
<table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/css/jquery.fileupload.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/css/jquery.fileupload-ui.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/vendor/jquery.ui.widget.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-process.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-validate.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var maxFileSizeBytes = ${maxFileSizeBytes};
if (maxFileSizeBytes < 0) {
//-1 or any negative value means no size limit
//set to undefined
//https://stackoverflow.com/info/5795936/how-to-set-a-javascript-var-as-undefined
maxFileSizeBytes = void 0;
}
//https://github.com/blueimp/jQuery-File-Upload/wiki/Options
//https://stackoverflow.com/info/34063348/jquery-file-upload-basic-plus-ui-and-i18n
//https://stackoverflow.com/info/11337897/how-to-customize-upload-download-template-of-blueimp-jquery-file-upload
$('#fileupload').fileupload({
url: '${pageContext.request.contextPath}/app/uploadResources.do',
fileInput: $('#fileuploadInput'),
acceptFileTypes: /(\.|\/)(jrxml|png|jpe?g)$/i,
maxFileSize: maxFileSizeBytes,
messages: {
acceptFileTypes: '${fileTypeNotAllowedText}',
maxFileSize: '${fileTooLargeMBText}'
},
filesContainer: $('.files'),
uploadTemplateId: null,
downloadTemplateId: null,
uploadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-upload fade">' +
'<td><p class="name"></p>' +
'<strong class="error text-danger"></strong>' +
'</td>' +
'<td><p class="size"></p>' +
'<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">' +
'<div class="progress-bar progress-bar-success" style="width:0%;"></div></div>' +
'</td>' +
'<td>' +
(!index && !o.options.autoUpload ?
'<button class="btn btn-primary start" disabled>' +
'<i class="glyphicon glyphicon-upload"></i> ' +
'<span>${startText}</span>' +
'</button>' : '') +
(!index ? '<button class="btn btn-warning cancel">' +
'<i class="glyphicon glyphicon-ban-circle"></i> ' +
'<span>${cancelText}</span>' +
'</button>' : '') +
'</td>' +
'</tr>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(file.error);
}
rows = rows.add(row);
});
return rows;
},
downloadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-download fade">' +
'<td><p class="name"></p>' +
(file.error ? '<strong class="error text-danger"></strong>' : '') +
'</td>' +
'<td><span class="size"></span></td>' +
'<td>' +
(file.deleteUrl ? '<button class="btn btn-danger delete">' +
'<i class="glyphicon glyphicon-trash"></i> ' +
'<span>${deleteText}</span>' +
'</button>' : '') +
'<button class="btn btn-warning cancel">' +
'<i class="glyphicon glyphicon-ban-circle"></i> ' +
'<span>${clearText}</span>' +
'</button>' +
'</td>' +
'</tr>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(file.error);
}
if (file.deleteUrl) {
row.find('button.delete')
.attr('data-type', file.deleteType)
.attr('data-url', file.deleteUrl);
}
rows = rows.add(row);
});
return rows;
}
});
});
</script>
Пример загрузки и удаления обработчиков запросов
@PostMapping("/app/uploadResources")
public @ResponseBody
Map<String, List<FileUploadResponse>> uploadResources(MultipartHttpServletRequest request,
Locale locale) {
//https://github.com/jdmr/fileUpload/blob/master/src/main/java/org/davidmendoza/fileUpload/web/ImageController.java
//https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
Map<String, List<FileUploadResponse>> response = new HashMap<>();
List<FileUploadResponse> fileList = new ArrayList<>();
String deleteUrlBase = request.getContextPath() + "/app/deleteResources.do?filename=";
//http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartRequest.html
Iterator<String> itr = request.getFileNames();
while (itr.hasNext()) {
String htmlParamName = itr.next();
MultipartFile file = request.getFile(htmlParamName);
FileUploadResponse fileDetails = new FileUploadResponse();
String filename = file.getOriginalFilename();
fileDetails.setName(filename);
fileDetails.setSize(file.getSize());
try {
String message = saveFile(file);
if (message != null) {
String errorMessage = messageSource.getMessage(message, null, locale);
fileDetails.setError(errorMessage);
} else {
//save successful
String encodedFilename = URLEncoder.encode(filename, "UTF-8");
String deleteUrl = deleteUrlBase + encodedFilename;
fileDetails.setDeleteUrl(deleteUrl);
}
} catch (IOException ex) {
logger.error("Error", ex);
fileDetails.setError(ex.getMessage());
}
fileList.add(fileDetails);
}
response.put("files", fileList);
return response;
}
@PostMapping("/app/deleteResources")
public @ResponseBody
Map<String, List<Map<String, Boolean>>> deleteResources(@RequestParam("filename") List<String> filenames) {
Map<String, List<Map<String, Boolean>>> response = new HashMap<>();
List<Map<String, Boolean>> fileList = new ArrayList<>();
String templatesPath = Config.getTemplatesPath();
for (String filename : filenames) {
Map<String, Boolean> fileDetails = new HashMap<>();
String cleanFilename = ArtUtils.cleanFileName(filename);
String filePath = templatesPath + cleanFilename;
File file = new File(filePath);
boolean deleted = file.delete();
if (deleted) {
fileDetails.put(cleanFilename, true);
} else {
fileDetails.put(cleanFilename, false);
}
fileList.add(fileDetails);
}
response.put("files", fileList);
return response;
}
Пример класса для генерации требуемого json-ответа
public class FileUploadResponse {
//https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
private String name;
private long size;
private String error;
private String deleteType = "POST";
private String deleteUrl;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the size
*/
public long getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(long size) {
this.size = size;
}
/**
* @return the error
*/
public String getError() {
return error;
}
/**
* @param error the error to set
*/
public void setError(String error) {
this.error = error;
}
/**
* @return the deleteType
*/
public String getDeleteType() {
return deleteType;
}
/**
* @param deleteType the deleteType to set
*/
public void setDeleteType(String deleteType) {
this.deleteType = deleteType;
}
/**
* @return the deleteUrl
*/
public String getDeleteUrl() {
return deleteUrl;
}
/**
* @param deleteUrl the deleteUrl to set
*/
public void setDeleteUrl(String deleteUrl) {
this.deleteUrl = deleteUrl;
}
}
См. https://pitipata.blogspot.co.ke/2017/01/using-jquery-file-upload-ui.html