Laravel 7 - Uncaught ReferenceError: Dropzone is not defined - javascript

I have a form that uses Dropzone for uploading images. The framework used is Laravel 7. The images are uploaded regularly to the store and inserted into the database, but in the console I get the following error:
Uncaught ReferenceError: Dropzone is not defined.
Also the page does not refresh or redirect.
View
<form data-single="true" data-file-types="image/jpeg|image/png|image/jpg" action="inserisci_avatar" class="dropzone " id="dropzone-avatar" method="POST" >
#csrf
<div class="fallback">
<input name="avatar" type="file" />
</div>
<div class="dz-message" data-dz-message>
<div class="text-lg font-medium">Trascina il tuo avatar qui.</div>
<div class="text-gray-600"> Oppure clicca e seleziona il file </div>
</div>
</form>
<script>
window.onload = function() {
//Dropzone.autoDiscover = false;
Dropzone.options.dropzoneAvatar = {
maxFilesize: 12,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 5000,
success: function(file, response)
{
console.log(response);
},
error: function(file, response)
{
return false;
}
};
};
</script>
Controller:
public function ins_avatar(Request $request)
{
$azienda = Auth::user();
if ($request->hasFile('file')) {
$id = $azienda->azienda->id;
$ins_avatar = Azienda::find($id);
if ($ins_avatar->avatar != null) {
$cancella = $ins_avatar->avatar;
Storage::delete('public/' . $cancella);
}
$path = $request->file('file')->store('uploads/avatar', 'public');
$ins_avatar->avatar = $path;
$ins_avatar->save();
$ok = 'ok';
return response()->json(['success' => $ok]);
} else {
return back()->with('avatar modificato', 'Nessuna immagine รจ stata caricata');
}
}
Grazie

Related

How To Delete Uploaded Files In Dropzone.js With ASP.NET Core MVC?

Im using DropzoneJS to upload Multiple files on my project.
I save the files in "wwwroot/ODIUpload" with new names using "Guid" in my "GeneratorClass" & Save the images name in OrderDetailImagesUpload Table in Database.
Now, after uploading the images, i want to if the user press delete button, the image will be deleted in "wwwroot/ODIUpload".
How can I do that?
View & Save Location Pic
View Code:
<div class="col-md-12">
<div id="dropzone ">
<form action="/Package/Design/#Model.OrderDetailID" method="post" enctype="multipart/form-data"
id="myAwesomeDropzone" class="dropzone">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="OrderDetailID"/>
<span asp-validation-for="ImageName" class="validation-error uplood-error"></span>
#Html.AntiForgeryToken()
<div></div>
<div class=" text-center">
<span class="uploadicon"> <i class="fal fa-images"></i> </span>
<div class="dz-message needsclick">
<button type="button" class="dz-button uploadicontext"> Upload Here</button><br/>
</div>
</div>
</form>
</div>
Js Code:
<script>
function myParamName() {
return "files";
}
Dropzone.options.myAwesomeDropzone = {
paramName: myParamName, // The name that will be used to transfer the file
maxFiles: 10,
dictRemoveFile: "Delete",
maxFilesize: 100,
uploadMultiple: true,
acceptedFiles: ".jpeg,.jpg,.png",
addRemoveLinks: true,
accept: function (file, done) {
if (file.name === "justinbieber.jpg") {
done("Naha, you don't.");
}
else { done(); }
},
};
</script>
Controller:
Upload Action:
[Authorize]
[Route("Package/Design/{id}")]
[HttpPost]
public IActionResult ODetailImages(OrderDetailImagesUpload _detailImagesUpload, ICollection<IFormFile> files)
{
if (files.Count() == 0)
{
ModelState.AddModelError("ImageName", "Upload Order Pics");
return View("OrderDetailImgUpload");
}
if (ModelState.IsValid)
{
_productService.AddOrderDetailImagesUpload(_detailImagesUpload.OrderDetailID, files);
return RedirectToAction("ShowBasket");
}
return View("OrderDetailImgUpload");
}
Services:
AddOrderDetailImagesUpload Service:
public void AddOrderDetailImagesUpload(int OrderDetailID, ICollection<IFormFile> imgups)
{
if (imgups != null && imgups.Any())
{
foreach (IFormFile file in imgups)
{
if (file.IsImage())
{
OrderDetailImagesUpload ODIU = new OrderDetailImagesUpload()
{
OrderDetailID = OrderDetailID,
ImageName = Generator.GetImageName() + Path.GetExtension(file.FileName)
};
_context.Add(ODIU);
string savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/ODIUpload",
ODIU.ImageName);
using (var stream = new FileStream(savePath, FileMode.Create))
{
file.CopyTo(stream);
}
_context.SaveChanges();
}
}
}
}
I don't know how to return the names of the images to the view and assign each of them to the delete button.

Dropzone doesn't bind other fields to Asp.Net Core viewmodel

I am using the following html to render a dropzone. And my controller is accepting IFormFile and FileViewModel. However dropzone does not bind my input tag which accepts a persons name to the viewModel on form submit.
I have also come to the resolution that Dropzone.js is a very old Ajax control primmed for single page applications.
HTML :
#model Dropzone.Models.FileViewModel
<form action="/Account/Create" enctype="multipart/form-data" method="POST">
<input type="text" id ="Username" name ="Username" asp-for="Model.Name" />
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
</form>
<div>
<button type="submit" id="submit-all"> upload </button>
</div>
JQuery:
<script>
Dropzone.options.myDropzone = {
url: "/Account/Create",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
acceptedFiles: "image/*",
init: function () {
var submitButton = document.querySelector("#submit-all");
var wrapperThis = this;
submitButton.addEventListener("click", function () {
wrapperThis.processQueue();
});
this.on("addedfile", function (file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn btn-lg dark'>Remove File</button>");
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
wrapperThis.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
this.on('sendingmultiple', function (data, xhr, formData) {
formData.append("Username", $("#Username").val());
});
}
};
</script>
Dropzone doesn't bind other fields to Asp.Net Core viewmodel
To add other fields with the upload files, you could use the sending event to add the field's value in the formData objects, instead of the sendingmultiple event.
Check the following sample:
public class FileViewModel
{
public string Name { get; set; }
public IFormFile File { get; set; }
public List<IFormFile> Files { get; set; }
}
Controller:
public IActionResult UploadFile()
{
FileViewModel model = new FileViewModel() { Name = "new File" };
return View(model);
}
[HttpPost]
public IActionResult UploadFile(FileViewModel fileViewModel, List<IFormFile> files)
{
try
{
if (files.Count > 0)
{
//string folderRoot = Path.Combine(_environment.ContentRootPath, "Uploads");
//string filePath = Guid.NewGuid() + Path.GetExtension(file.FileName);
//filePath = Path.Combine(folderRoot, filePath);
//using (var stream = new FileStream(filePath, FileMode.Create))
//{
// await file.CopyToAsync(stream);
//}
}
return Ok(new { success = true, message = "File Uploaded" });
}
catch (Exception)
{
return BadRequest(new { success = false, message = "Error file failed to upload" });
}
}
View Page:
#model WebApplication6.Models.FileViewModel
#{
ViewData["Title"] = "UploadFile";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>UploadFile</h1>
<form asp-action="UploadFile" enctype="multipart/form-data" method="POST">
<div class="form-group">
#*<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>*#
<input type="text" asp-for="Name" />
<div class="dropzone" id="dropzone-form" name="mainFileUploader">
<div class="fallback">
<input asp-for="File" type="file" multiple />
</div>
</div>
</div>
<div class="form-group">
<button type="button" id="submit-all"> upload </button>
</div>
</form>
Add the following JQuery scripts:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<link rel="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script>
<script type="text/javascript">
Dropzone.options.dropzoneForm = {
url: "/Test/UploadFile",
paramName: "file",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
acceptedFiles: "image/*",
init: function () {
var submitButton = document.querySelector("#submit-all");
var wrapperThis = this;
submitButton.addEventListener("click", function () {
wrapperThis.processQueue();
});
this.on("addedfile", function (file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn btn-lg dark'>Remove File</button>");
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
wrapperThis.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
this.on("sending", function (file, response, formData) {
formData.append("Name", $("#Name").val());
formData.append("Files", file);
});
//this.on('sendingmultiple', function (data, xhr, formData) {
// formData.append("Name", $("#Name").val());
//});
}
};
</script>
}
The result like this:

File not uploading when uploading with AJAX using symfoy

I am developing an application and i want to upload a picture using Ajax with symfony 3.4. Sorry if i am missing anything because i am new to AJAX. I am following the step from https://codepen.io/dsalvagni/pen/BLapab
I am getting the 200 response from symfony but the files doesnt upload.
Entity:
/**
* #ORM\Column(type="string", length=255)
* #var string
*/
private $image;
/**
* #Vich\UploadableField(mapping="profile_image", fileNameProperty="image")
* #var File
*/
private $imageFile;
Here is my controller:
public function testAction(Request $request)
{
$testEntry = new Test();
$form = $this->createForm(TestType::class, $testEntry);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $testEntry->getImageFile();
$fileName = md5(uniqid()) . '.' . $file->guessExtension();
$photoDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/images';
$file->move($photoDir, $fileName);
$testEntry->setImage($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($testEntry);
$em->flush();
if ($request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'Success!', 'success' => true), 200);
}
if ($request->isMethod('POST')) {
return new JsonResponse(array('message' => 'Invalid form', 'success' => false), 400);
}
return $this->redirect($this->generateUrl('homepage'));
}
return $this->render('#Alumni/Default/test.html.twig',
['form' => $form->createView()]);
}
and here is my html.twig
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_row(form.name) }}
<div class="profile">
<div class="photo">
{{ form_widget(form.imageFile, {'attr': {'class': 'file-upload'}}) }}
<div class="photo__helper">
<div class="photo__frame photo__frame--circle">
<canvas class="photo__canvas"></canvas>
<div class="message is-empty">
<p class="message--desktop">Drop your photo here or browse your computer.</p>
<p class="message--mobile">Tap here to select your picture.</p>
</div>
<div class="message is-loading">
<i class="fa fa-2x fa-spin fa-spinner"></i>
</div>
<div class="message is-dragover">
<i class="fa fa-2x fa-cloud-upload"></i>
<p>Drop your photo</p>
</div>
<div class="message is-wrong-file-type">
<p>Only images allowed.</p>
<p class="message--desktop">Drop your photo here or browse your computer.</p>
<p class="message--mobile">Tap here to select your picture.</p>
</div>
<div class="message is-wrong-image-size">
<p>Your photo must be larger than 350px.</p>
</div>
</div>
</div>
<div class="photo__options hide">
<div class="photo__zoom">
<input type="range" class="zoom-handler">
</div><i class="fa fa-trash"></i>
</div>
<button type="button" id="uploadBtn">Upload</button>
</div>
</div>
{{ form_row(form.submit, { 'label': 'Submit me' }) }}
{{ form_end(form) }}
here is my route
test:
path: /test
defaults: {_controller: AlumniBundle:Default:test}
here is my js
$(function() {
/**
* DEMO
*/
var p = new profilePicture('.profile', null,
{
imageHelper: true,
onRemove: function (type) {
$('.preview').hide().attr('src','');
},
onError: function (type) {
console.log('Error type: ' + type);
}
});
$('#uploadBtn').on('click', function() {
var image = p.getAsDataURL();
$.post("/test", { image: image });
});
and i am getting 200 response but i cannot locate the file:
Many thanks in advance for your help
It won't upload because your function isn't sending any file.
It's just sending the file name at most.
The Function
function ajaxSubmit(node) {
$.ajax({
type: node.attr("method"), // Method on form tag
url: node.attr("action"), // Action on form tag
enctype: "multipart/form-data", //needed to upload files
data: new FormData(node[0]), // The form content
processData: false,
contentType: false,
cache: false
}).done(function(response, status, xhr) {
console.info(response);
}).fail(function(request, status, error) {
console.error(request);
console.error(status);
console.error(error);
});
}
The Action
$(body).on("submit", ".ajs", function(e) {
e.preventDefault(); // Prevent default HTML behavior
ajaxSubmit($(this)); //Handle submit with AJAX
});
The View
// Add 'ajs' class to forms that should be submited with AJAX
{{ form_start(form, {'class': 'ajs'}) }}

Symfony2: manually submit a form without class via AJAX

We have an old website where I have implemented a form that is sent by AngularJS to a PHP script and after processing an email message get sent. If the form is not valid the PHP script returns a JSON with the validation errors. Since we already use Symfony for some other applications (REST APIs), I thought it would be nice to reimplement my plain PHP script in Symfony.
For the sake of simplicity I put only a small but relevant fragment of my code. This is what I have:
HTML (ng-app is bound on body tag, not shown here):
<form name="infoscreenForm" class="form-horizontal" enctype="multipart/form-data" ng-controller="FormController">
<div class="form-group">
<div class="col-lg-1 control-label">*</div>
<div class="col-lg-11 input-group">
<input type="text" class="form-control" id="contact_person"
name="contact_person" ng-model="formData.contactPerson"
placeholder="Kontaktperson">
</div>
<span class="text-warning" ng-show="errors.contactPerson">
{{ errors.contactPerson }}
</span>
</div>
<div class="form-group">
<div class="col-lg-1 control-label">*</div>
<div class="col-lg-11 input-group">
<span class="input-group-addon">#</span>
<input type="email" class="form-control" id="email" name="email"
ng-model="formData.email" placeholder="E-Mail">
</div>
<span class="text-warning" ng-show="errors.email">
{{ errors.email }}
</span>
</div>
<div class="form-group">
<div class="col-lg-1 control-label"> </div>
<div class="col-lg-11 input-group">
<input type="file" class="form-control" id="file" name="file"
file-model="formData.file"
accept="application/pdf,image/jpeg,image/png">
</div>
<span class="text-warning" ng-show="errors.file">
{{ errors.file }}
</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" id="submit"
name="submit" ng-click="submitForm()">
Formular absenden
</button>
</div>
</form>
JS:
var app = angular.module('InfoscreenApp', []);
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
app.factory('multipartForm', ['$http', function ($http) {
return {
post : function (uploadUrl, data) {
var fd = new FormData();
for (var key in data) {
fd.append(key, data[key]);
}
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers : { 'Content-Type': undefined }
});
}
};
}]);
app.controller('FormController', ['$scope', 'multipartForm', function ($scope, multipartForm) {
$scope.formData = {};
$scope.submitForm = function () {
var uploadUrl = 'http://localhost:8000/infoscreen';
multipartForm.post(uploadUrl, $scope.formData)
.then(function (data) {
console.log(data);
if (data.success) {
$scope.message = data.data.message;
console.log(data.data.message);
} else {
$scope.errors = data.data.errors;
}
});
};
}]);
With the plain PHP script everything works fine. Here is what I tried to do in Symfony:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
class DefaultController extends Controller
{
/**
* #Route("/infoscreen", name="infoscreen")
*/
public function infoscreenAction(Request $request)
{
$defaultData = array('message' => 'infoscreenForm');
$form = $this->createFormBuilder($defaultData)
->add('contactPerson', TextType::class, array(
'constraints' => array(
new NotBlank(),
)
))
->add('email', EmailType::class, array(
'constraints' => array(
new NotBlank(),
new Email(),
)
))
->add('file', FileType::class)
->add('submit', SubmitType::class)
->getForm();
;
$form->submit($request->request->get($form->getName()));
$data = $form->getData();
if ($form->isValid()) {
echo 'Alles ok';
// send an email
}
$errors = array();
$validation = $this->get('validator')->validate($form);
foreach ($validation as $error) {
$errors[$error->getPropertyPath()] = $error->getMessage();
}
$response = new Response();
$response->setContent(json_encode(array(
'form_data' => $data,
'errors' => $errors,
)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
CSRF is disabled in config.yml. The form is not bound to an entity class. After submitting the form I get the following object in the console:
{
data: Object,
status: 200,
config: Object,
statusText: "OK"
}
The important part is in data: Object:
{
form_data: {
contactPerson: null,
email: null,
message: "infoscreenForm",
file: null
},
errors : {
children[contactPerson].data = "This value should not be blank",
children[email].data = "This value should not be blank"
}
}
This happens when I submit the form with some values entered in the fields. It seems that the submitted data is not bound to the form in the controller. I'm probably missing something, but I stuck here and have no idea how to proceed. I tried with $form->bind($request), $form->handleRequest($request) and few other things, but it didn't work. Even if I bind the fields individually, I still don't get their values in the form.
Can somebody please help me.
Thanks in advance.
Try
$this->get('form.factory')->createNamedBuilder(null, 'form', $defaultData)
instead of
$this->createFormBuilder($defaultData)

jQuery-File-Upload - Output

I use the jQuery-File-Upload. The form data is written to the database as I want to.
But when I upload an image I receive the following message:
{"files":[{"name":"1430606695-9544","size":0,"type":"","error":"No file was uploaded"}]}
Why does it say "No file was uploaded" etc.?
index.php:
<?php
/*
* jQuery File Upload Plugin PHP Example 5.14
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
$options = array(
'delete_type' => 'POST',
'db_host' => 'localhost',
'db_user' => 'helloworld',
'db_pass' => 'helloworld',
'db_name' => 'helloworld',
'db_table' => 'files'
);
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
class CustomUploadHandler extends UploadHandler {
protected function initialize() {
$this->db = new mysqli(
$this->options['db_host'],
$this->options['db_user'],
$this->options['db_pass'],
$this->options['db_name']
);
parent::initialize();
$this->db->close();
}
protected function handle_form_data($file, $index) {
$file->title = #$_REQUEST['title'][$index];
$file->description = #$_REQUEST['description'][$index];
}
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = parent::handle_file_upload(
$uploaded_file, $name, $size, $type, $error, $index, $content_range
);
if (empty($file->error)) {
$sql = 'INSERT INTO `'.$this->options['db_table']
.'` (`name`, `size`, `type`, `title`, `description`)'
.' VALUES (?, ?, ?, ?, ?)';
$query = $this->db->prepare($sql);
$query->bind_param(
'sisss',
$file->name,
$file->size,
$file->type,
$file->title,
$file->description
);
$query->execute();
$file->id = $this->db->insert_id;
}
return $file;
}
protected function set_additional_file_properties($file) {
parent::set_additional_file_properties($file);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$sql = 'SELECT `id`, `type`, `title`, `description` FROM `'
.$this->options['db_table'].'` WHERE `name`=?';
$query = $this->db->prepare($sql);
$query->bind_param('s', $file->name);
$query->execute();
$query->bind_result(
$id,
$type,
$title,
$description
);
while ($query->fetch()) {
$file->id = $id;
$file->type = $type;
$file->title = $title;
$file->description = $description;
}
}
}
public function delete($print_response = true) {
$response = parent::delete(false);
foreach ($response as $name => $deleted) {
if ($deleted) {
$sql = 'DELETE FROM `'
.$this->options['db_table'].'` WHERE `name`=?';
$query = $this->db->prepare($sql);
$query->bind_param('s', $name);
$query->execute();
}
}
return $this->generate_response($response, $print_response);
}
}
$upload_handler = new CustomUploadHandler($options);
basic-plus.html
<form id="fileupload" action="server/php/" method="POST" enctype="multipart/form-data">
<!-- 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>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
<label class="title">
<span>Title:</span><br>
<input name="title[]" class="form-control" value="testtitel">
</label>
<label class="description">
<span>Description:</span><br>
<input name="description[]" class="form-control" value="testdescription">
</label>
</form>
<script>
/*jslint unparam: true, regexp: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === 'blueimp.github.io' ?
'//jquery-file-upload.appspot.com/' : 'server/php/',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.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($('<span class="text-danger"/>').text(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 .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
main.js
/*
* jQuery File Upload Plugin JS Example 8.9.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global $, window */
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
url: 'server/php/'
}).on('fileuploadsubmit', function (e, data) {
data.formData = data.context.find(':input').serializeArray();
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// 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),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
});
}
});
what does your network stack say?
ie: go to the "developer" view in chrome, (view->Developer->Developer Tools),
and open up the "network" tab, and try to do an upload, and look at the request, response, etc.
that may shed a lot of light.
I have used this plugin with javascript and java, but not with php.
also: find a really simple example that uploads a file (with php, if you need to use that), and start building out from there.

Categories

Resources