javascriptuploadcare

Uploadcare - How to set the value of the Image URL?


I have a number of pictures displayed on a user's webpage and I want to give the user the ability to select and crop any images. I am using uploadcare widget to allow the user to perform that. In simple words, all I want to achieve is, a user selects an image and the URL of that image get updated to the value of the input and so the widget opens up and allows the user to crop the image and upload it. I will then use the UUID of the edited image and replace the image with the older image.

I am using this as guidance:Image Cropping for Web Apps with Uploadcare.

I have the widget's code in main HTML page with the value set to empty string but I am not able to update the value when the user selects an image. I have also tried to dynamically create a form with JavaScript code but that also doesn't work.

This if the form which contains the code for the widget

<form id="form_crop_image_id" action="" >
<input
      id="crop_image"
      name="crop_edit_image"
      value=""
      type="hidden"
      role="uploadcare-uploader"
      data-images-only
      data-crop
/>
<button class="btn" id ="edit_picture_btn" type="button" </button>
</form>

This is how I am trying to update the value of the element in the form

form_object_id = document.forms['form_crop_image_id'];
form_object_id.elements['crop_edit_image'].value = image_url;//var holds the selected image url
console.log(form_object_id.elements['crop_edit_image'].value);

My expected behaviour would be that a user selects an image and the URL is set to the value so that the user can edit that particular image. The actual behaviour is that the value remains set and cannot be modified. Any helps will be appreciated.


Solution

  • Only Uploadcare CDN URLs are allowed to be set as the value of the widget's input field if you want to preload a file. If the images on your page are not hosted at Uploadcare, you need to upload them to Uploadcare first to be able to edit them in the widget. You can do this programmatically with the uploadcare.fileFrom method. Before this, you need to get a widget instance to be able to update the widget's value with the file instance created from a URL.

    // get an instance of the widget
    var widget = uploadcare.Widget('[role=uploadcare-uploader]');
    // create a file instance from the URL of the image selected
    var file = uploadcare.fileFrom('url', image_url);
    // preload the file to the widget
    widget.value(file);
    // open widget's dialog
    widget.openDialog('preview');
    

    Then, after cropping/editing, you can get the modified URL this way

    widget.onChange(function (file) {
      file.done(function (fileInfo) {
        // log the updated URL to console or do anything you need with it
        console.log(fileInfo.cdnUrl);
      });
    });