What is the process for assigning one file input to another file input?

Quite an unusual question, I admit. The crux of the matter is my utilization of a fantastic tool known as cropit. With this tool, we have the ability to upload an image, preview it, and then manipulate it according to our preferences.

HTML:

<div align="center" id="image-cropper1">

    <!-- This is where users can select a new image -->
  <label class="btn btn-success btn-file">Upload Photo<input type="file" class="cropit-image-input"/></label><br><br>

  <!-- This is where the preview image will be displayed -->
  <label><div class="cropit-preview"><img class="prepic" src="preloadimage.jpg"></label>

<!-- Here is how you can process the image -->
<button type="button" id="image1pick" class="btn btn-primary" data-dismiss="modal" disabled>OK</button></div>

JQuery:

$('#image-cropper1').cropit();

$('#image-cropper1').change(function() {
    $('#image1pick').prop('disabled', false);
    });

$('#image1pick').click(function() {
    imageData1 = $('#image-cropper1').cropit('export', {originalSize: true});
    $.post('somephp.php', { imageData1: imageData1 }, function() { $('#image1pick').data('clicked', true) })
    });

My goal now is to integrate another <input type="file"/> button that enables the uploading of 6 images simultaneously and displays them in 6 separate ".cropit-preview" divs. This is crucial because users can zoom in and rotate the images within the previews. Is there a way to achieve this with multiple files while still adhering to the structure of this tool?

EDIT:

Please refer to the documentation: The issue lies in the structure. Let's say I need three different croppers. The layout would appear as follows:

JQuery:

$('#image-cropper1').cropit();
$('#image-cropper2').cropit();
$('#image-cropper3').cropit();

HTML:

<!-- Cropper No 1 -->
<div id="image-cropper1">
<input type="file" class="cropit-image-input" />
<div class="cropit-preview"></div>
</div>

<!-- Cropper No 2 -->
<div id="image-cropper2">
<input type="file" class="cropit-image-input" />
<div class="cropit-preview"></div>
</div>

<!-- Cropper No 3 -->
<div id="image-cropper3">
<input type="file" class="cropit-image-input" />
<div class="cropit-preview"></div>
</div>

As shown above, each file input and preview div are contained within their respective numbered divs. However, I now aim to introduce one input option that can upload three images at once and correspondingly fit into every image-preview displayed within each numbered div. How can this objective be accomplished?

Answer №1

If you want to transfer the file selection from one input field to another, you can achieve it with this code snippet:

const sourceInput = document.querySelector('#source-input>input[type=file]');
const targetInput = document.querySelector('#target-input>input[type=file]');
targetInput.files = sourceInput.files;

When dealing with <input type="file"> elements, the files attribute refers to a FileList object, which is explained in more detail here.

Answer №2

Give this a shot:

$("#targetFileInput").prop("files",$("#originalFileInput").prop("files"));

Answer №3

I came up with a solution that looks like this:

//custom.js
var doc, C;
$(function(){
  doc = document;
  C = function(tag){
    return doc.createElement(tag);
  }
  $('#upload').change(function(ev){
    var output = $('#output'), files = this.files, fileLength = files.length;
    if(fileLength > 6){
      console.log('Too many files');
    }
    else{
      var container = C('div');
      $.each(files, function(index, value){
        var reader = new FileReader, img = C('img'), canvas = C('canvas'), ctx = canvas.getContext('2d');
        reader.onload = function(event){
          img.onload = function(){
            canvas.width = this.width; canvas.height = this.height; ctx = canvas.getContext('2d'); ctx.drawImage(this, 0, 0); container.append(canvas);
          }
          img.src = event.target.result;
        }
        reader.readAsDataURL(value);
      });
      output.append(container);
    }
  });
  $('#send').click(function(){
    var formData = new FormData;
    $('canvas').each(function(i, element){
      e.toBlob(function(blob){
        var fileReader = new FileReader;
        fileReader.onloadend = function(){
          formData.append('image_'+i, fileReader.result); 
          formData.append('count', i+1);
        }
        fileReader.readAsArrayBuffer(blob);
      });
    });

    
  });


});
/* custom.css */
html,body{
  margin:0; padding:0;
}
.main{
  width:980px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <link type='text/css' rel='stylesheet' href='custom.css' />
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
    <script type='text/javascript' src='custom.js'></script>
  </head>
<body>
  <div class='main'>
    <form>
      <input type='file' multiple='multiple' id='upload' />
      <input type='button' id='send' value='Send to Server' />
    </form>
    <div id='output'></div>
  </div>
</body>
</html>

Answer №4

To link the source input tag file to another one, you can simply follow these steps:

Suppose we have a pair of input tags named source and target.

<input id="source" type="file" name="file" accept=".jpg,.jpeg,.png" multiple="multiple" aspect="1">
<input id="target" type="file" name="file" accept=".jpg,.jpeg,.png" multiple="multiple" aspect="1">
let source = document.getElementById("source");
let target = document.getElementById("target");
source.files = target.files;

Credit goes to Ourobonus for the helpful tip.

If your goal is to display only the image thumbnails, you may find useful information at

https://developer.mozilla.org/en-US/docs/web/api/file_api/using_files_from_web_applications
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS Accordion Component: A Handy Tool for Organ

I have been trying to implement an Accordion in my angular project by sending HTML structure from a controller. However, despite following the documentation closely, the Accordion is not displaying as expected. Here is a snippet of the code I am using: v ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

Having trouble with the performance of a kendo UI treeview connected to a JSON

I have successfully implemented a kendo UI tree using an external JSON file. Everything works fine when I have around 200 nodes, but it takes too long when dealing with a large amount of data. You can view the implementation here. Below is the jQuery co ...

Elevate your website with Bootstrap 4's compact floating icon menu

I've been searching online, but I can't seem to find exactly what I need. My goal is to create a compact Sidebar menu that stays on the left side and is centered. The only solution I came across was this: `https://codepen.io/kemsly/pen/mJxwJg` ...

Some components react to history.push() with react-router-dom while others simply don't seem to respond

As the title states, I am using React-router-dom in my App.js file with a Router containing multiple Routes and a Switch. I have been successful in manipulating history and navigating my app using useHistory and history.push() in smaller components. Howev ...

Tips for organizing your JSON Structure within ReactJs

In the given example, I have a JSON structure with information about different airlines. The Airline Name is dynamic and we need to separate the JSON into an expected array format. const arr = [ { Airline: "Goair", Departure: "01:50" ...

What is the best way to increment the value of an input by any number using JavaScript and HTML?

My code is causing a NaN error, and I'm struggling to identify the root cause. Even providing a specific number in the addnum function did not resolve the issue. <script> var result = document.getElementById("result"); var inputVal = ...

Differences in behavior across operating systems when pasting content copied from Excel into Next.js

Exploring the Issue I am currently working on a project using Next.js 14 where users can paste data copied from an Excel file into a spreadsheet-like component called react-data-grid. However, I have encountered some inconsistencies when copy-pasting on M ...

Tips for transferring a function from a Node.js server to a client

Hey everyone, I'm trying to achieve the following: On the Node server side: var fn = function(){ alert("hello"); } I am looking for a way to send this function to the client side. I am currently using AngularJS, but I am open to other solution ...

Avoiding the insertion of duplicates in Angular 2 with Observables

My current issue involves a growing array each time I submit a post. It seems like the problem lies within the second observable where the user object gets updated with a new timestamp after each post submission. I have attempted to prevent duplicate entr ...

What are the best practices for creating a contemporary website that functions effectively on IE7?

After creating several websites for my clients, I discovered that they are not functioning well in IE7. Unfortunately, there is still a small percentage of people using IE7. Can anyone suggest a super quick solution to fix this issue? Feel free to recomm ...

Creating a navigation bar in React using react-scroll

Is anyone able to assist me with resolving the issue I am facing similar to what was discussed in React bootstrap navbar collapse not working? The problem is that although everything seems to be functioning properly, the navbar does not collapse when cli ...

Python web scraping: Extracting data from HTML tag names

Seeking help with extracting user data from a website by retrieving User IDs directly from tag names. I am utilizing python selenium and beautiful soup to extract the UID specifically from the div tag. For instance: <"div id="UID_**60CE07D6DF5C02A987E ...

Server side Meteor with reactive coffee on client

Is it possible to run 'client' Meteorite packages on the server? I want to implement reactive coffee for generating a newsletter on the server. I haven't been able to find any information on this, even though it seems like a logical choice. ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

Display alert only when focus is lost (on blur) and a dropdown selection was not made

Utilizing Google Maps Places for autocompletion of my input, I am aiming to nudge the user towards selecting an address from the provided dropdowns in order to work with the chosen place. A challenge arises when considering enabling users to input address ...

Is there a way to properly center this text vertically within the row?

The kids are like puzzle pieces. I've experimented with different classes like justify-content-center, align-items-center, and text-center, but no luck. All I want is for the text to be perfectly centered both vertically and horizontally within the ...

Is it possible for a div nested within another div to still occupy space on the page despite being set

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $("select#choosebook").change(function(){ $(".title").slideDown(" ...

Creating Multiple Choice Forms in React: A Guide to Implementing Conversational Form

I've been exploring React (Next.js) and I came across an interesting example of how to use multiple choice in simple HTML on Codepen ([https://codepen.io/space10/pen/JMXzGX][1]). Now I'm curious about how to implement a similar functionality in R ...

Bookmarklet in JavaScript that automatically extracts and displays Meta keywords in a new tab within the browser

I successfully implemented a script that extracts site meta keywords and writes them into the DOM. javascript:(function metaKeywords() { metaCollection = document.getElementsByTagName('meta'); for (i=0;i<metaCollection.length;i++) { nameAttri ...