Showing posts with label fine-uploader. Show all posts
Showing posts with label fine-uploader. Show all posts

Thursday, September 6, 2018

Can't call any fineUploader methods in callback function

Leave a Comment

I have autoUpload set to false, as I want to upload the images myself to my backend. However, to do this I first need the file object. In the callbacks onSubmitted event I'm trying to pass the images id to the getFile method, to return the object. However, when I try to do this I get the below error message.

in onSubmitted: id=0 | name=28603454_15219061700_r.jpg index.js:2178

[Fine Uploader 5.16.2] Caught exception in 'onSubmitted' callback - Cannot read property 'uploader' of null

I'm guessing I get this because I'm declaring a const object and referencing it at the same time, which I believe you cannot do...

So, any ideas on how I can call methods within the callbacks function? Or is there another way?

const uploader = new FineUploaderTraditional({   options: {     maxConnections: 1,     autoUpload: false,     deleteFile: { enabled: true, endpoint: "/uploads" },     request: { endpoint: "/uploads" },     retry: { enableAuto: true },     callbacks: {       onSubmitted: function(id, name) {         console.log("in onSubmitted: id=" + id + " | name=" + name);         // getFile(id) returns a `File` or `Blob` object.         console.log(this.uploader.getFile(id));       }     }   } }); 

Update I've now taken all of my fine-uploader code and created a new component with it. I'm still facing the same problems. The component code below:

FineUploader.jsx

import React, { Component } from "react"; import FineUploaderTraditional from "fine-uploader-wrappers"; import Gallery from "react-fine-uploader"; import Filename from "react-fine-uploader/filename"; import "react-fine-uploader/gallery/gallery.css";  const util = require("util");  const uploader = new FineUploaderTraditional({   options: {     // debug: true,     maxConnections: 1,     autoUpload: false,     deleteFile: { enabled: true, endpoint: "/uploads" },     request: { endpoint: "/uploads" },     retry: { enableAuto: true },     validation: {       acceptFiles: ".jpg,.png,.gif,.jpeg",       allowedExtensions: ["jpg", "png", "gif", "jpeg"],       itemLimit: 5,       sizeLimit: 5000000     },     callbacks: {       onCancel: function() {         console.log("in onCancel: ");       },       onComplete: function(id, name, responseJSON, xhr) {         console.log("in onComplete: " + id + " | " + name + " | " + responseJSON + " | " + xhr);       },       onAllComplete: function(succeeded, failed) {         console.log("in onAllComplete: " + succeeded + " | " + failed);       },       onProgress: function(id, name, uploadedBytes, totalBytes) {         console.log("in onProgress: " + id + " | " + name + " | " + uploadedBytes + " | " + totalBytes);       },       onError: function(id, name, errorReason, xhr) {         console.log("in onError: " + id + " | " + name + " | " + errorReason + " | " + xhr);       },       onDelete: function(id) {         console.log("in onDelete: " + id);       },       onDeleteComplete: function(id, xhr, isError) {         console.log("in onDeleteComplete: " + id + " | " + xhr + " | " + isError);       },       onPasteReceived: function(blob) {         console.log("in onPasteReceived: " + blob);       },       onResume: function(id, name, chunkData, customResumeData) {         console.log("in onResume: " + id + " | " + name + " | " + chunkData + " | " + customResumeData);       },       onStatusChange: function(id, oldStatus, newStatus) {         console.log("in onStatusChange: " + id + " | " + oldStatus + " | " + newStatus);       },       onSubmit: function(id, name) {         console.log("in onSubmit: " + id + " | " + name);       },       onSubmitted: function(id, name) {         console.log("in onSubmitted: id=" + id + " | name=" + name);         // getFile(id) returns a `File` or `Blob` object.         // console.log(this.uploader.getFile(id));         // console.log(uploader.getFile(id));         // nothing here is working.... :(       },       onUpload: function(id, name) {         console.log("in onUpload: " + id + " | " + name);       },       onValidate: function(data, buttonContainer) {         console.log(           "in onValidate: " + util.inspect(data, { showHidden: true, depth: null }) + " | " + buttonContainer         );       },       onSessionRequestComplete: function(response, success, xhrOrXdr) {         console.log("in onSessionRequestComplete: " + response + " | " + success + " | " + xhrOrXdr);       }     }   } });  const fileInputChildren = <span>Click to Add Photos</span>; const statusTextOverride = {   upload_successful: "Success!" };  class FineUploader extends Component {   constructor() {     super();      this.state = {       submittedFiles: []     };   }    componentDidMount() {     uploader.on("submitted", id => {       const submittedFiles = this.state.submittedFiles;       console.log("submittedFiles: " + submittedFiles);        submittedFiles.push(id);       this.setState({ submittedFiles });     });   }    render() {     return (       <div>         {this.state.submittedFiles.map(id => (           <Filename id={id} uploader={uploader} />         ))}         <Gallery           fileInput-children={fileInputChildren}           status-text={{ text: statusTextOverride }}           uploader={uploader}         />       </div>     );   } }  export default FineUploader; 

And -- On the main page now, I'm importing FineUploader.jsx, and using the component.

import FineUploader from "../../components/FineUploader"; 

In my render method I have:

<FineUploader /> 

1 Answers

Answers 1

this is tricky in javascript. Within regular functions (e.g., function f(){...}), this depends on where the function is called rather than where it is defined. When using callbacks via a 3rd party api, you don't really have control over where it is called, so you can end up with errors like you have above.

Fortunately, you can use arrow functions (e.g., const f = () => {...};) to bind this based on where the function is defined.

See the MDN docs for more info or you can reference this excellent SO answer.

For your code in particular, however, I am not sure that either of those will work as your this when you define onSubmitted is just the global/window object.

In order for this to work, you need to create a closure at the top level (right before you actually create the uploader):

function onSubmitted(id, name) {     console.log("in onSubmitted: id=" + id + " | name=" + name);     // getFile(id) returns a `File` or `Blob` object.     console.log(uploader.getFile(id)); }  const uploader = new FineUploaderTraditional({..., callbacks: {onSubmitted, ...}}); 

This will allow you to define the logic for interacting with uploader before you actually instantiate it (which is what it looks like you want). Notice the lack of this as we are simply taking advantage of js closure rules.

Read More

Tuesday, June 26, 2018

FineUploader failing to POST

Leave a Comment

I'm trying to implement file uploading using FineUploader. Everything is working except the actual upload - when I select a file, it is instantly added to the page saying "Upload failed". Looking at the Network tab in Firefox's inspector, no POST request is even happening, and I'm getting an error message from FineUploader saying the response is not valid JSON (go figure).

Here's my client-side (partial) view:

<div id="fine-uploader"></div>  @* This section is rendered into the page header *@ @section Scripts {     <script src="/Scripts/fine-uploader/jquery.fine-uploader.js"></script>     <link href="/Scripts/fine-uploader/fine-uploader-new.css" rel="stylesheet" />      @* The following template is copied from the Validation example at https://fineuploader.com/demos.html in the jQuery tab *@     <script type="text/template" id="qq-template">         <div class="qq-uploader-selector qq-uploader" qq-drop-area-text="Drop files here">             <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">                 <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>             </div>             <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>                 <span class="qq-upload-drop-area-text-selector"></span>             </div>             <div class="qq-upload-button-selector qq-upload-button">                 <div>Select files</div>             </div>             <span class="qq-drop-processing-selector qq-drop-processing">                 <span>Processing dropped files...</span>                 <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>             </span>             <ul class="qq-upload-list-selector qq-upload-list" aria-live="polite" aria-relevant="additions removals">                 <li>                     <div class="qq-progress-bar-container-selector">                         <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>                     </div>                     <span class="qq-upload-spinner-selector qq-upload-spinner"></span>                     <img class="qq-thumbnail-selector" qq-max-size="100" qq-server-scale>                     <span class="qq-upload-file-selector qq-upload-file"></span>                     <span class="qq-upload-size-selector qq-upload-size"></span>                     <button type="button" class="qq-btn qq-upload-cancel-selector qq-upload-cancel">Cancel</button>                     <button type="button" class="qq-btn qq-upload-retry-selector qq-upload-retry">Retry</button>                     <button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete">Delete</button>                     <span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>                 </li>             </ul>              <dialog class="qq-alert-dialog-selector">                 <div class="qq-dialog-message-selector"></div>                 <div class="qq-dialog-buttons">                     <button type="button" class="qq-cancel-button-selector">Close</button>                 </div>             </dialog>              <dialog class="qq-confirm-dialog-selector">                 <div class="qq-dialog-message-selector"></div>                 <div class="qq-dialog-buttons">                     <button type="button" class="qq-cancel-button-selector">No</button>                     <button type="button" class="qq-ok-button-selector">Yes</button>                 </div>             </dialog>              <dialog class="qq-prompt-dialog-selector">                 <div class="qq-dialog-message-selector"></div>                 <input type="text">                 <div class="qq-dialog-buttons">                     <button type="button" class="qq-cancel-button-selector">Cancel</button>                     <button type="button" class="qq-ok-button-selector">Ok</button>                 </div>             </dialog>         </div>     </script>     }  <script>     $("#fine-uploader").fineUploader({         template: "qq-template",         request: {             // Generates the following absolute URL (have also tried relative, neither work)             // http://localhost:49450/MyController/UploadFile             endpoint: "@Url.Action("UploadFile", "My", null, Request.Url.Scheme)"         },         debug: true,         thumbnails: {             placeholders: {                 waitingPath: "@Url.Content("~/Scripts/fine-uploader/placeholders/waiting-generic.png")",                 notAvailablePath: "@Url.Content("~/Scripts/fine-uploader/placeholders/not_available-generic.png")"             }         },         validation: {             allowedExtensions: ["jpg", "png"],             sizeLimit: 1048576 // 1 MB = 1024 * 1024 bytes         },         text: {             fileInputTitle: ""         }     }); </script> 

And my MVC 4 controller code (FineUpload is a class from the nuget package of the same name):

public class MyController : Controller {     // This method is never being hit     [HttpPost]     public FineUploaderResult UploadFile(FineUpload qqfilename) {         return new FineUploaderResult(true);     } } 

And here's Firefox's console log after attempting an upload (I've omitted all the success messages preceding this regarding thumbnail loading etc.):

[Fine Uploader 5.16.2] Sending simple upload request for 0 util.js:236:16 [Fine Uploader 5.16.2] xhr - server response received for 0 util.js:236:16 [Fine Uploader 5.16.2] responseText = util.js:236:16 [Fine Uploader 5.16.2] Received response status 0 with body: util.js:236:16 [Fine Uploader 5.16.2] Error when attempting to parse xhr response text (JSON.parse: unexpected end of data at line 1 column 1 of the JSON data) util.js:241:20 [Fine Uploader 5.16.2] Simple upload request failed for 0 util.js:236:16 

The code looks fine to me but the network activity log shows no POST requests are being made at all. Why would that be?

0 Answers

Read More

Saturday, November 18, 2017

Fine-Uploader: setParams not adding new parameter to subsequent requests

Leave a Comment

My domain layer requires an entity to have 1:N images associated with it.

As FineUploader sends each image as a separate request, i am creating an entity (server side) on the first request and sending the ID of that back in the first response JSON to be added to the subsequent requests, so that the remaining images have an entity relationship ID to be saved with. This is all working well, except the new ID returned from the first request is not being appended to the next request.

I am using setParams to append the ID by hooking onto the onComplete event, as follows:

var uploader = new qq.FineUploader({         debug: true,         element: document.getElementById('fine-uploader'),         allowedExtensions: ['jpg', 'jpeg', 'bmp', 'png','gif'],         callbacks : {             onComplete : function(id, name, responseJSON){                 this.setParams({entityId: responseJSON.entityId});             }         }     }); 

The new param is not added to request URI or post data. What am i doing wrong?

(Using FineUploader 5.15.3, debugged on FireFox Developer Edition, PHP 7.1 server side)

1 Answers

Answers 1

Just a wild guess (I do not have the environment to try it myself):

var entityId = '';  var uploader = new qq.FineUploader({         debug: true,         // *** This is the part I added         request: {              params: { entityId: entityId }         },         element: document.getElementById('fine-uploader'),         allowedExtensions: ['jpg', 'jpeg', 'bmp', 'png','gif'],         callbacks : {             onComplete : function(id, name, responseJSON){                 //**** This is the part I changed                 entityId = responseJSON.entityId;                 // this.setParams({entityId: responseJSON.entityId});             }         }     }); 

Basically what I intend to do is to get the entityId from the response and feed it as a parameter to the next request.

I hope it helps.

Read More

Tuesday, June 20, 2017

Troubleshooting failed file upload for FineUploader

Leave a Comment

I'm using React version of FineUploader and getting both "PUT request failed" and "put blob call failed" errors when I try to upload a file -- see below: enter image description here

The next line "Received error response" doesn't really tell me anything. Just gives me the HTML of my page.

I did set up my CORS settings with PUT, DELETE and OPTIONS -- see below: enter image description here

and the following shows my FineUploader instantiation.enter image description here

The link to the fine uploader implementation is at http://ingridapp.azurewebsites.net/home/test

What could be causing this issue?

UPDATE: I'm actually not seeing any calls to my Azure container. Checked both in Chrome and Fiddler. I don't think a call to Azure is being made.

enter image description here enter image description here

0 Answers

Read More

Wednesday, March 23, 2016

AWS S3 upload. Invalid according to Policy: Policy expired

Leave a Comment

I'm using a Django server hosted on EC2 Singapore. I'm also using an S3 bucket that is used to save files uploaded through the Django Admin panel. To upload files, I'm using django-s3direct.

When I upload files, using my local machine on Eastern American time, it prevents me from uploading the files citing:

<Message>Invalid according to Policy: Policy expired.</Message> 

I've tried the solutions from: Fine Uploader getting "Policy expired" message sending to S3 for some and here: https://github.com/FineUploader/fine-uploader/issues/1387

When I check the uploaded time and the UTC time, there's no difference. How do I fix this error?

EDIT: To be noted, the upload works perfectly on localhost but doesn't work on the server hosted on AWS EC2.

2 Answers

Answers 1

Similar issues refer to an inaccurate clock. This should be the clock of the client not the server. I suggest writing code to check whether client's time in sync with a known and accurate time server. If the time is out of sync, a friendly message can be shown to the user to update the system's clock. If the time is in sync, you can then proceed with the upload.

Answers 2

i use Amazon EC2 and S3 bucket, i dont have problems with S3, but i use django-storages and boto, and i dont have problems, try use this.

Read More