FineUploader deleting with servlets - javascript

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"
}
}

Related

How to make loop function using multiple input value to JSL in Groovy

I'm using the below function in Jenkins Shared Library.
/* The below function delete uploads that exist in the server. */
def delete_upload(server_url,each_upload_id,authentication){
def delete_upload_url = server_url + "/api/v1/uploads/" + each_upload_id
def response = httpRequest consoleLogResponseBody: true,
contentType: 'APPLICATION_JSON',
customHeaders: [[maskValue: false, name: 'id ', value: each_upload_id],
[maskValue: false, name: 'Authorization', value: authentication]],
httpMode: 'DELETE', ignoreSslErrors: true, responseHandle: 'NONE', url: delete_upload_url,
validResponseCodes: '100:599'
if(response.status == 202){
def result = readJSON text: """${response.content}"""
return result['message'].toString()
}
else {
throw new Exception("Incorrect upload id! Please give the correct upload id.")
}
}
====================================================================================================
I'm getting below response,
Response Code: HTTP/1.1 202 Accepted
Response:
{"code":202,"message":"Delete Job for file with id 2","type":"INFO"}
Success: Status code 202 is in the accepted range: 100:599
====================================================================================================
Purpose: I'm using the above JSL function to delete a uploads in the web server using upload id.
Requirement:
I need to delete multiple uploads by using multiple upload id's (like each_upload_id in 1,2,3 etc) using this JSL delete function.
Need to pass the upload id's in loops and delete the uploads in the web server.
Any suggestions, please ?
Are you looking for something like this?
def idList = ["1", "2", "3"]
try {
idList.each{ id =>
delete_upload(server_url,id,authentication)
}
} catch(e) {
println "Error occurred!"
}

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

Unable to view image on thumbnail in fine-uploader

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.

Symfony: Send variable throught GET to handler from Ajax

I would like to use AJAX in my Symfony3.0.3 project.
The communication works, but I can't get variable from JS to the handler. In the direction handler to JS, it works fine.
I'm trying to get the variable from the request with "$request->query->get('id'))" but I only get "null".
In an other way I'm trying to use the variable from the URL but I get this error:
"An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("id") to generate a URL for route "admin_ajax".") in CommonBundle:Default:index.html.twig at line 421."
I don't mind using a solution or an other (I'll use the best one depending of your advices), but I still would like the solution for both error.
JS
function selectClient(idClient)//idClient = 1
{
alert(idClient);
$.post('{{path('admin_ajax')}}',{idClient: id},
function(response)
{
if(response.code == 100 && response.success)
{
alert(response.id);//Show null if using $request->query->get('id')) in handler but should be 1
}}, "json");
}
routing:
admin_ajax:
defaults: { _controller: CommonBundle:Default:getClient }
path: /ajax/{id}
handler:
public function getClientAction($id)
{
$request = $this->container->get('request_stack')->getCurrentRequest();
$isAjax = $request->isXMLHttpRequest();
if ($isAjax)
{
$response = array("code" => 100, "success" => true, "id" => $request->query->get('id'));
return new Response(json_encode($response));
}
$response = array("code" => 0, "success" => false);
return new Response(json_encode($response));
}
EDIT:
Thank for Rim, and Rvanlaak answer, I used the FOSJsRoutingBundle.
JS
function selectClient(idClient)
{
$.get(Routing.generate('ajax_getclient', { id:idClient }),
function(response)
{
if(response.code == 100 && response.success)
{
alert(response.id);
}
else
}, "json");
}
routing:
ajax_getclient:
defaults: { _controller: CommonBundle:Default:getClient }
path: /ajax/{id}
options:
expose: true
Note that the option "expose: true" was necessary to works.
Thats because the twig is executing before javascript so he is not reconizing the client id param
i had the same problem and resolve it using FOSJSRoutingBundle see this post :
Ajax url parametetr using Twig path

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;
}

Categories