Unable to view image on thumbnail in fine-uploader - javascript

Hi I am working on upload feature which has been done successfully using fine uploader, but for new functionality for edit i searched for same plugin and found that session can handle this functionality.
but i am not getting view of image in fine uploader section as below is the view i am getting.
I am passing name,uuid and thumbnailUrl as response.
Edited:
At Server Side:
List<PropertyImageEntity> propertyImageEntity=propertyService.getImagesUrlNames(Integer.parseInt(request.getParameter("id")),Constant.PROP_VAL);
for(PropertyImageEntity propertyImagesDetails: propertyImageEntity)
{
ImageDataResponse imageResponseData=new ImageDataResponse();
imageResponseData.setName(propertyImagesDetails.getFilename());
String test=String.valueOf(UUID.randomUUID());
imageResponseData.setUuid(this.uuid);
imageResponseData.setId(String.valueOf(propertyImagesDetails.getImageid()));
imageResponseData.setSize(propertyImagesDetails.getSize());
imageResponseData.setStatus("upload successful");
imageResponseData.setThumbnailUrl(propertyImagesDetails.getUrl());
imageResponse.add(imageResponseData);
}
at client side:
var manualUploader1 = new qq.FineUploader(
{
element : document
.getElementById('fine-uploader-manual-trigger1'),
template : 'qq-template-manual-trigger1',
request : {
endpoint : '/server/uploads?${_csrf.parameterName}=${_csrf.token}&id=${id}'
},
thumbnails : {
placeholders : {
waitingPath : '../assets/js/property/fileupload/placeholders/waiting-generic.png',
notAvailablePath : '../assets/js/property/fileupload/placeholders/not_available-generic.png'
}
},
validation : {
allowedExtensions : [ 'png', 'jpeg', 'jpg' , 'gif'],
itemLimit : 6,
sizeLimit : 100000000
},
autoUpload : false,
debug : true,
callbacks: {
onError: function(id, name, errorReason, xhrOrXdr) {
$("#errorMsg4").html(errorReason);
}
},
session: {
endpoint: '/server/get?id=${id}',
params: {},
customHeaders: {},
refreshOnReset: true
},
messages: {
typeError: jQuery.i18n.prop("invalid.extention.error"),
sizeError: jQuery.i18n.prop("upload.filesize.error"),
noFilesError: jQuery.i18n.prop("nofiles.toupload.error"),
tooManyItemsError: jQuery.i18n.prop("toomany.items.error"),
retryFailTooManyItems: jQuery.i18n.prop("retry.fail.error")
}
});
qq(document.getElementById("trigger-upload1")).attach("click",
function() {
$("#errorMsg4").html("");
manualUploader1.uploadStoredFiles();
});
but response for image url in console showing 200 ok.
Response:
[{"name":"b.png","uuid":"e3a5581e-aee9-4b8d-813f-63e0d400c9bc","thumbnailUrl":"http://192.168.1.68/html/1465290007617b.png","id":"84","size":26507,"status"
:null}]
Console Log:

The above problem was solved by adding cors headers in apache2.conf.
Header set Access-Control-Allow-Origin "*"
Thanks to #Ray for his answer on this post.

Related

Fine-uploader Initial File List onStatusComplete null result

I want to do the same feature as found in this SO Post ;
But in the onStatusChange callback the objects are null.
callbacks: {
onStatusChange: function(id, oldStatus, newStatus) {
console.log('new status of ' + newStatus + ' for ID: ' + id);
console.log(this.getItemByFileId(id));
}
I get the following output
new status of upload successful for ID: 0
fine-uploader.min.js:2 [Fine Uploader 5.14.2] Caught exception in 'onStatusChange' callback - Cannot read property 'className' of null
I know session response from my server is OK, b/c fine-uploader displays my file, filename and the delete button.
Is what I'm trying to do supported?
Here's my full fine-uploader code for reference:
`
var uploader_132963 = new qq.FineUploader({
element: document.getElementById("uploader_132963"),
session: { endpoint: 'https://localhost/session', params : { account: 'DEMO9', index: 1, psuuid: UUID_UPLOAD1},},
template : 'qq-template1',
debug: true,
request : {
endpoint: 'localhost',
},
autoUpload: true,
retry: {
enableAuto: true
},
multiple: false,
concurrent: {
enabled: false
},
chunking: {
concurrent: {
enabled : false,
},
enabled: true,
mandatory: true,
partSize: 2000000,
success: {
endpoint: 'https://localhost/success'
}
},
deleteFile: {
enabled: true,
endpoint: 'https://localhost',
method: 'POST',
},
extraButtons: {
folders: false
},
validation: {
allowedExtensions: ['3g2','asf','avi','bmp','doc','docx','flv','gif','jpeg','jpg','m4a','m4v','mj2','mov','mp3','mp4','pdf','png','ppt','pptx','svg',],
allowEmpty: false,
itemLimit: 1,
sizeLimit: 1024000000,
},
callbacks: {
onStatusChange: function(id, oldStatus, newStatus) {
if (newStatus == qq.status.UPLOAD_SUCCESSFUL) {
var fileItem = this.getItemByFileId(id); // will throw exception here
}
}
}
})
`
I had the exact same issue as described here. The solution was as pointed out by bobflorian. This is how I handle both canned files loaded from the server normal uploaded files:
onAllComplete: function( arrSucceeded, arrFailed,) {
if (arrSucceeded!==null && $.isArray(arrSucceeded)){
for (var i=0,x=arrSucceeded.length;i<x;i++){
//Get the template markup for the uploaded file
var fileItem = this.getItemByFileId(arrSucceeded[i]);
//Get the generated uuid. This is the same uuid that we save in the PHP SESSION. It points to the actual uploaded file
var uuid = this.getUuid(arrSucceeded[i]);
}
}
}
I'm using version 5.16.2. Ray, you did a fantastic job with this library.
Moving my code to the onAllComplete callback gives the desired result when loading files via the Initial File List. The onStatusChange doesn't seem to have the getItemByFileId function available under this at that point in time. It will throw an exception of
Caught exception in 'onStatusChange' callback - Cannot read property 'className' of null

FineUploader deleting with servlets

I am quite new to this topic and this is my first time using FineUploader. I am currently using a Servlet to handle client requests and it works perfectly fine for "POST" but not for delete. The doDelete method in my servlet is never being called. Am I missing something here ?
var manualUploader = new qq.FineUploader({
element : document.getElementById('fine-uploader-manual-trigger'),
template : 'qq-template-manual-trigger',
request : {
endpoint : 'UploadServlet',
filenameParam : 'filename',
},
deleteFile : {
enabled : true,
endpoint : 'UploadServlet',
method : 'DELETE'
forceConfirm : true,
},
thumbnails : {
placeholders : {
waitingPath : 'fine-uploader/placeholders/waiting-generic.png',
notAvailablePath : 'fine-uploader/placeholders/not_available-generic.png'
}
},
autoUpload : false,
debug : true
});
The console output :
fine-uploader.js:3961 DELETE http://localhost:8081/test/UploadServlet/0036839e-3f58-466b-a6d3-05b3f66cedda? 403 (Forbidden)
fine-uploader.js:257 [Fine Uploader 5.9.0] DELETE request for 0 has failed - response code 403 fine-uploader.js:257
fine-uploader.js:257 [Fine Uploader 5.9.0] Delete request for 'file.png' has failed.
Try with below code for delete file option.
deleteFile: {
enabled: true,
endpoint: "UploadServlet",
forceConfirm: true,
params: {
foo: "bar"
}
}

Jquery : Post Request is breaking while uploading multiple images

I am using Plupload js plugin to upload multiple images in one request. This plugin is working like if someone adding 5 images at a time then post request will go 5 times to upload each of images separately. As we know Post request require unique csrf token but in my case due to same token after one time, post request is failing.
Here is my code ...
<c:set var="csrfTokenVal"><csrf:token-value uri="<%=request.getRequestURI()%>"/></c:set>
<script>
var csrftokenV="${csrfTokenVal}";
$("#uploader").plupload({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url:'/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+csrftokenV,
// User can upload no more then 20 files in one go (sets multiple_queues to false)
max_file_count: 10,
chunk_size: '1mb',
// Resize images on clientside if we can
resize : {
width : 600,
height : 610,
quality : 90,
//crop: true // crop to exact dimensions
},
filters : {
// Maximum file size
max_file_size : '1mb',
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
]
},
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
// Views to activate
views: {
list: true,
thumbs: false, // Show thumbs
active: 'thumbs'
},
init: {
FilesAdded: function(up, files) {
$("#uploader_filelist").show();
},
FileUploaded: function(up, file, info, res) {
var imageObjectArray=$.parseJSON(info.response);
for(i=0;i<imageObjectArray.objectList.length; i++){
$('#showfilelist ul').append("<li><a class='delIcon-image' href='#delete' id='delSurgeryImageIcon'></a><a id=" + imageObjectArray.objectList[i].uid + " class='cboxElement imguid' href='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' target='_blank'><img src='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' border='0'>"+"</a> <strong>"+noteAddedMsg+"</strong><span class='image-created'>"+imageObjectArray.objectList[i].formattedDate+" "+byMsg+" "+imageObjectArray.objectList[i].userName+" </span></li>");
}
$("#uploader_filelist").empty().hide();
_SPINE.colorboxOverlay.coloboxPopup();
_SPINE.surgeryNotes.deleteImages();
$(".plupload_done .plupload_file_thumb").removeClass("hide")
},
ChunkUploaded: function (up, file, response) {
response = $.parseJSON(response.response || "null");
if (response.chunk == 3) {
up.stop();
up.start();
}
console.log(file.loaded);
}
},
// Flash settings
flash_swf_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.swf',
// Silverlight settings../assets/js
silverlight_xap_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.xap'
});
</script>
Here you can see I am generating scrf token (csrftokenV) and sending it in url to make it post supported.
Now the problem is if I am uploading more than 1 images (lets say 3), then 3 time post request will go. Each time i will get same csrf token and after uploaing first image, furthure images will not work and i will get this exception ....
WARNING: potential cross-site request forgery (CSRF) attack thwarted (user:<anonymous>, ip:127.0.0.1, uri:/**/image, error:request token does not match session token)
Please help me to solve this problem. Thanks
Finally One of my friend had solved the issue. It can't be possible to handle this issue through client side script so we leverage the power of Java. We had updated the csrfToken based on new request and sent it out with response.
Here is a solution ..
private String updateToken(HttpServletRequest request)
{
final HttpSession session = request.getSession(false);
CsrfGuard csrfGuard = CsrfGuard.getInstance();
csrfGuard.updateTokens(request);
String newToken=(String) session.getAttribute(REQUEST_TOKEN);
return newToken;
}
Setting newToken in response ...
response.setResult(this.updateToken(request));
return response;
Now we can change the url in beforeUpload event and set new token in the url.
BeforeUpload: function(up, file)
{
up.settings.url='/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+tokenRefresh
}
FileUploaded: function(up, file, info, res)
{
var imageObjectArray=$.parseJSON(info.response);
tokenRefresh=imageObjectArray.result;
}

Fine-Uploader: fail to load a thumbnail from the server

I want to draw a thumbnail genenerated by my server after successful uploading.
My code:
function createUploader() {
var uploader = new qq.FineUploader({
element: document.getElementById('uploader_button'),
multiple: false,
display: {
fileSizeOnSubmit: true
},
request: {
endpoint: '/upload/newDocument',
params: {
token: '********'
}
},
/* ...settings... */
callbacks: {
onComplete: updatePicture
}
});
function updatePicture() {
uploader.drawThumbnail(document.getElementById('picture'), 200, true);
};
};
Html:
<img id="picture" src="/preview/empty.jpg" class="qq-thumbnail-selector">
Server response:
{"success":true,"thumbnailUrl":"\/preview\/00a64818c21a35ab59a342cc3e41182e50c06fa3528b128db22bb0.33508816.jpg"}
Fine-Uploader log output:
[FineUploader 4.0.3] xhr - server response received for 0 fineuploader-4.0.3.min.js:16
[FineUploader 4.0.3] responseText = {"success":true,"thumbnailUrl":"\/preview\/00a64818c21a35ab59a342cc3e41182e50c06fa3528b128db22bb0.33508816.jpg"} fineuploader-4.0.3.min.js:16
[FineUploader 4.0.3] Received response status 200 with body: {"success":true,"thumbnailUrl":"\/preview\/00a64818c21a35ab59a342cc3e41182e50c06fa3528b128db22bb0.33508816.jpg"} fineuploader-4.0.3.min.js:16
updatePicture function invokes successfully after uploading, but no thumbnail is drawn.
What is wrong in my code? What should I do to draw a thumbnail?
The problem is that you are not calling the drawThumbnail method correctly. Per the documentation, the first parameter is the ID of the associated file. So, your onComplete callback should look like this:
onComplete: function(id) {
updatePicture(id)
}
and your updatePicture function must be changed to:
function updatePicture(fileId) {
uploader.drawThumbnail(fileId, document.getElementById('picture'), 200, true);
}

Extjs 4 upload success function does not react

i have a grid with an toolbar and on that toolbar an upload option is added, so the upload is alright and it works , but after the file was uploaded to the server the success function does not react.
here my upload code:
upload: function () {
Ext.create('Ext.window.Window', {
title: 'Upload',
width: 300,
layout: 'fit',
draggable: false,
resizable: false,
modal: true,
bodyPadding: 5,
items: [{
xtype: 'form',
bodyPadding: 10,
frame: true,
items: [{
xtype:'filefield',
name:'file',
fieldLabel: 'File',
buttonText: 'Select File',
labelWidth: 30,
anchor: '100%'
}, {
xtype: 'button',
text: 'Upload',
handler: function(){
var form = this.up('form').getForm();
if(form.isValid()){
form.submit({
method: 'POST',
url: 'http://localhost:3000/upload',
success: function (form, action) {
Ext.Msg.alert('Success', 'Your File has been uploaded.');
console.log(action);
},
failure : function (form,action) {
Ext.Msg.alert('Error', 'Failed to upload file.');
}
})
}
}
}]
}],
}).show();
},
});
and the server response :
app.post('/upload', function(req, res) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Content-Type','application/json; charset=UTF8');
var tmp_path = req.files.file.path;
var newPath = __dirname + '/files/' + req.files.file.name;
fs.rename(tmp_path, newPath, function (err){
if (err) throw err;
});
var path = newPath;
var name = req.files.file.name;
connection.query('SELECT name FROM audio WHERE name = ?', [name] , function(err,result) {
if (result[0]) {
console.log('File already exist');
res.status(400).send(JSON.stringify());
} else {
connection.query('INSERT INTO audio (name, path) VALUES (?,?)', [name,path], function (err,result) {
if (err) throw err;
var test = {
success: true
};
res.send({success:true});
console.log('success');
});
}
});
});
i can provide more code if necessary, thanks in advance
The error message is explicit: your response is lost due to cross-domain iframe issue.
See the doc explanation of how file upload form are handled: a hidden iframe is created to receive the response from the server (because, before HTML5 it was not possible to upload a file using XHR). When the iframe is loaded, Ext parses its content to read the response.
But, it is only allowed for a page to manipulate its iframes content if both are on the same domain, including the port number.
Most probably you're accessing your page at http://localhost/, while you're posting your form to http://localhost:3000. So forbidden: error, and no response for you!
This is a Ext js bug identified by Uberdude in the Sencha Forum.
Description of the problem :
When you make an Ext.Ajax.request with a form containing a file input to be uploaded, or manually set the isUpload option to true, rather than doing a proper Ajax request Ext submits the form in the standard HTML way to a dynamically generated hidden . The json response body is then read out of the iframe to create a faked-up Ajax response. A problem arises if the page making the upload Ajax request has changed its document.domain property, e.g. a page at home.example.com includes resources from static.example.com which it wishes to manipulate with javascript without violating the browser's same-origin-policy, so both set their document.domain to "example.com". If home.example.com then makes an upload Ajax request to a url on the home.example.com server, the iframe into which the response is written will have its document.domain as "home.example.com". Thus when the ExtJS code within Ajax.request on the home.example.com page tries to extract the document body from the iframe, it will be blocked by the same-origin-policy and the response passed to the callback functions will incorrectly have empty responseText.
Work Around :
1. Pass the document.domain to the server when making the upload request.
2. In your server response, add the document.domain in your response text/html.
response.setHeader('Content-Type', 'text/html');
response.write('document.domain = "' + params.__domain + '";');
response.write(JSON.stringify({msg: 'Welcome ' + params.name}));
response.end('');
Detail :
Please refer to :
http://www.sencha.com/forum/showthread.php?136092-Response-lost-from-upload-Ajax-request-to-iframe-if-document.domain-changed

Categories