Dropzone.JS отправляет файлы и данные формы в одном запросе

Я использую dropzone.js в своей существующей форме для хранения изображений, могу ли я хранить изображения одновременно с сохранением формы? Я имею в виду, отправить изображения, сброшенные в dropzone по тому же запросу, что и форма?

     {{ Form::open(array('method'=>'post','class'=> 'ajaxaddevent','url' =>
'/savenewevent', 'enctype' => 'multipart/form-data')) }}
<div class="form-group">
<label for="name">Título do Evento</label>
<input type="text" id="name" name="name" class="form-
control" />
</div>

<div class="form-group">
<label for="eventtype">Tipo</label>
<select class="form-control selecttype" name="eventtype" id="eventtype">
@foreach ($eventtypes as $eventtype)
<option value="{{ $eventtype->id }}" > {{ $eventtype->name }} </option>
@endforeach
</select>
</div>

<div class="form-group">
<label for="eventsubtype">Sub-tipo</label>
<select class="form-control selectsubtypes" name="eventsubtype" id="eventsubtype">
@foreach ($eventsubtypes as $eventsubtype)
<option value="{{ $eventsubtype->id }}" > {{ $eventsubtype->name }} </option>
@endforeach
</select>
</div>

<div class="form-group">
<label for="eventsubtype">Temas</label>
<span class="interest_text">podes escolher mais que um</span>
<div class="interests_list submit_event">
@foreach ($themes as $theme)
<div>
<input type="checkbox" id="theme{{ $theme->id }}" name="themes[]" value="{{ $theme->id }}"/>
<label for="theme{{ $theme->id }}"><span></span>{{ $theme->name }}</label>
</div>
@endforeach
</div>
</div>

<div class="row">
<div class="form-group col-md-6">
<label for="startdate">Data</label>
<input type="date" id="startdate" name="startdate" class="form-control" data-country="PT" placeholder="Início">
</div>
<div class="form-group col-md-6">
<label for="enddate">&nbsp;</label>
<input type="date" id="enddate" name="enddate" class="form-control" data-country="PT" placeholder="Fim">
<span id="adddata" class="adddata">Adicionar mais horas</span>
</div>
</div>

<div class="row">
<div class="form-group col-md-6">
<label for="schedule_start">Horário</label>
<input type="date" id="schedule_start" name="schedule_start" class="form-control" data-country="PT" placeholder="Início">
</div>
<div class="form-group col-md-6">
<label for="schedule_end">&nbsp;</label>
<input type="date" id="schedule_end" name="schedule_end" class="form-control" data-country="PT" placeholder="Fim">
<span id="addschedule" class="addschedule">Adicionar mais horas</span>
</div>
</div>

<div class="form-group">
<label for="duration">Duração</label>
<input type="text" id="duration" name="duration" class="form-control" placeholder="Escreve apenas números" />
<div class="duration_tips">
<input type="radio" id="duration_tips_hours" name="duration_tips[]" value="hours" /><label for="duration_tips_hours"><span></span>Horas</label>
<input type="radio" id="duration_tips_weeks" name="duration_tips[]" value="weeks" /><label for="duration_tips_weeks"><span></span>Semanas</label>
<input type="radio" id="duration_tips_days" name="duration_tips[]" value="days" /><label for="duration_tips_days"><span></span>Dias</label>
<input type="radio" id="duration_tips_months" name="duration_tips[]" value="months" /><label for="duration_tips_months"><span></span>Meses</label>
</div>
</div>

<div class="form-group">
<label for="available">Número de vagas</label>
<input type="text" id="available" name="available" class="form-control" placeholder="Escreve apenas números" />
</div>

<div class="form-group">
<label for="price">Preço</label>
<input type="text" id="price" name="price" class="form-control" placeholder="Escreve apenas números" />
</div><div class="form-group">
<label for="email">E-mail</label>
<input type="email" id="email" class="form-control" />
</div>

<div class="form-group">
<label for="telemovel">Telemóvel</label>
<input type="text" id="telemovel" class="form-control" />
</div>

<div class="form-group">
<label for="distrito">Distrito / região</label>
<select class="form-control selectdistrict" name="districtID" id="districtID">
@foreach ($districts as $district)
<option value="{{ $district->id }}" > {{ $district->name }} </option>
@endforeach
</select>
</div>

<div class="form-group">
<label for="concelho">Concelho</label>
<select class="form-control selectcounties" name="countyID" id="countyID">
@foreach ($counties as $county)
<option value="{{ $county->id }}" > {{ $county->name }} </option>
@endforeach
</select>
</div>

<div class="form-group">
<label for="morada">Morada</label>
<input type="text" id="morada" class="form-control" />
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="freguesia">Freguesia</label>
<input type="text" name="parish" id="parish" class="form-control" />
</div>

<div class="form-group col-md-6">
<label for="cod_postal">Código Postal</label>
<input type="text" id="cod_postal" class="form-control" />
</div>
</div>

<div class="form-group">
<label for="website">Website</label>
<input type="text" id="website" class="form-control" />
</div>

<div class="form-group">
<label for="facebook">Facebook</label>
<input type="text" name="facebooklink" id="facebook" class="form-control" placeholder="www.facebook.com/" />
</div>

<div class="form-group">
<label for="descricao">Descrição</label>
<textarea id="description" name="description" class="form-control descricao_anunciante" placeholder="(quem és, o que fazes ou o que representas, temas e tipos de eventos)"></textarea>
</div>

<div class="dropzone" id="myDropzone"> </div>

<button type="submit" id="submit" class="btn btn-primary">GUARDAR DADOS</button>
{{Form::close()}}

JS

Dropzone.options.myDropzone= {
url: '/savenewevent',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 5,
maxFilesize: 1,
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {
dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

// for Dropzone to process the queue (instead of default form behavior):
document.getElementById("submit").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});

this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("name", jQuery("#name").val());
formData.append("eventtype", jQuery("#eventtype").val());
formData.append("eventtype", jQuery("#eventtype").val());
formData.append("eventsubtype", jQuery("#eventsubtype").val());
formData.append("startdate", jQuery("#startdate").val());
formData.append("enddate", jQuery("#enddate").val());
formData.append("schedule_start", jQuery("#schedule_start").val());
formData.append("schedule_end", jQuery("#schedule_end").val());
formData.append("available", jQuery("#available").val());
formData.append("price", jQuery("#price").val());
formData.append("email", jQuery("#email").val());
formData.append("telemovel", jQuery("#telemovel").val());
formData.append("districtID", jQuery("#districtID").val());
formData.append("morada", jQuery("#morada").val());
formData.append("cod_postal", jQuery("#cod_postal").val());
formData.append("website", jQuery("#website").val());
formData.append("facebook", jQuery("#facebook").val());
formData.append("description", jQuery("#description").val());
});
}
  • Отправьте изображения / файлы по одному и тому же запросу (я сделал var_dump, когда я нажимаю на кнопку отправки, а файлы из этой зоны отсутствуют), как я могу этого добиться?

ИЛИ ЖЕ

Моя цель состоит в том, чтобы сохранить сериализованный массив в базе данных с именами файлов, так что, если есть другая альтернатива, все в порядке.

Спасибо.

0

Решение

Чтобы достичь этого, вы можете сделать свою Dropzone autoProcessQueue затем верните в качестве истинного имя файла в качестве ответа после его загрузки и сохраните в форме ввода.

this.on("success", function (file, response) {
$('#hidden_input_id').val(response);
}

когда вы отправляете форму, вы получите имена файлов от имени #hidden_input_id и сохранить это имя в базе данных.

Примечание: URL-адрес загрузки ajax / изображения Dropzone и URL-адрес отправки формы должны отличаться.

пример кода выглядит так:
HTML

{{ Form::open(array('method'=>'post','class'=> 'ajaxaddevent','url' =>
'/savenewevent', 'enctype' => 'multipart/form-data')) }}

<input id="hidden_image_name" name="hidden_image_name"
<div class="dropzone" id="myDropzone"> </div>

<button type="submit" id="submit" class="btn btn-primary">GUARDAR DADOS</button>
{{Form::close()}}

и сценарий, как,

Dropzone.options.myDropzone= {
url: '/uploadimage',
autoProcessQueue: true,
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 5,
maxFilesize: 1,
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {
dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

// for Dropzone to process the queue (instead of default form behavior):
document.getElementById("submit").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});

this.on("success", function (file, response) {
$('#hidden_image_name').val(response);
}

}
};

/загрузить изображение Маршрут должен возвращать имя загруженного файла изображения.

В / savenewevent маршрут вы можете проверить опубликованные параметры и, если hidden_image_name не является пустой картой, отображающей это имя изображения для этого события.

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector