Having trouble uploading a file to a perl script with ajax/javascript

I am facing an issue with a form that is designed to upload a single file image to a Perl script. The problem arises when the Perl script does not receive the file stream correctly, resulting in a 0-byte file size. I suspect that there might be an error in passing the right name/reference from the HTML input to the JavaScript formdata.append function. For now, I am steering clear of jQuery and XHR version 2 solutions as I strive to troubleshoot and resolve this issue.

HTML Input:

<input id="newimg" type="file" onchange="changeimg(this.value,dbtable,dbid);">

JavaScript:

function changeimg(filename, dbtable, dbid) {

  // Ignore "c:\fakepath\" in filename
  var filename = document.getElementById('newimg').files[0].name;

  var formdata = new FormData();
  formdata.append("Content-Type", "multipart/form-data");
  formdata.append("dbtable", dbtable);
  formdata.append("dbid", dbid);
  formdata.append("filename", filename);

  if (window.XMLHttpRequest) {
      // Code for IE7+, Firefox, Chrome, Opera, Safari
      var xhr = new XMLHttpRequest();
  } else {
      // Code for IE6, IE5
      var xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhr.open("POST","/uploader.pl",true);
  xhr.send(formdata);

}

Perl snippet currently being used:

#
my $upload_filehandle = $cgi->upload("filename");
#
open (UPLOADFILE, ">$newfile");
      binmode UPLOADFILE;
      while ( <$upload_filehandle> ) {
        print UPLOADFILE;
      }
close UPLOADFILE;
#

Answer №1

Your current variables do not reference the file, which is why it's not being included in the process.

Instead of passing the filename, pass the input itself.

Update this line:

formdata.append("filename",filename);

to:

var file = document.getElementById("newimg").files[0];
formdata.append("newimg", file);

An even better approach would be to submit the entire form altogether:

<input id="newimg" name="newimg" type="file" onchange="changeimg(this.form)">

and

function changeimg(form) {
  var formdata = new FormData(form);
  var xhr = new XMLHttpRequest();
  xhr.open("POST","/uploader.pl",true);
  xhr.addEventListener("load", function () { alert("Loaded"); });
  xhr.send(formdata);
}

Answer №2

Special thanks to @Quentin for providing an example that helped me successfully implement the necessary changes. I found it important to include dbtable and dbid in the code as they were not part of the form variables.

Here is the updated HTML input:

<input type="file" name="filename" onchange="changeimg(this.form,dbtable,dbid);">

And here is the revised JavaScript function:

function changeimg(form, table, id) {
  var formdata = new FormData(form);
  formdata.append("item", id);
  formdata.append("table", table);
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/uploader.pl", true);
  xhr.addEventListener("load", function () { alert("Loaded"); });
  xhr.send(formdata);
}

No modifications were made to the Perl script.

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

Ensuring that hover remains active despite mousedown in JavaScript, CSS, and HTML

It appears that in browser-javascript hover events are deactivated when the mouse button is pressed down, as demonstrated by the following example: (Please run the code snippet to witness what I am referring to.) * { user-select: none; } #click, #drag, ...

What do you call the syntax %< ... >%?

Observed zoomInAnimation : true, zoomOutScale : false, templateLegend : "<ul class=\"<%=type.toLowerCase()%>-legend\"><% for (var j=0; j<sections.length; j++){%><li><span style=\"background-color:<%=section ...

`Custom transitions between sections using fullpage.js`

Has anyone used the fullpage.js extension to achieve an animation similar to this one, where sections are destroyed on scroll? ...

Issue: No default template engine specified and no file extension provided. (Using Express framework)

While I came across numerous questions with a similar title, they only provided me with partial help and did not completely resolve the error that plagued me. Just to provide some context, I had created a file named listing.js as a tool for running node c ...

What is the best way to transfer POST data using ajax requests?

Currently, I am in the process of developing a script that can effectively receive and parse a JSON array within the POST array. To start off, I am sending some random JSON data to my script so that I have something to work with. The receiving script is w ...

Populating check boxes in a jQuery multiselect dropdown based on option text

I want to implement the jQuery multiselect plugin, but the checkboxes are appearing after the option text. Is there a way to configure them to be on the left side? https://i.sstatic.net/2oB2y.png ...

What could be the reason my vue.js button is not generating a fresh textarea?

I am currently developing my first Web App with vue.js and I'm trying to implement a feature where clicking a button will generate a new textarea. It seemed to be functioning correctly when tested on jsfiddle, but once I tried running it in visual stu ...

Received an error while attempting to install react-router-dom

I keep encountering this error message whenever I try to install react-router-dom using NPM in VS Code: https://i.sstatic.net/hFshb.png npm ERR! Unexpected end of JSON input while parsing near '...stack-launcher":"^1.0' npm ERR! You can find ...

Best method for connecting user input with a class

I'm currently working with a WYSIWYG editor (Tinymce) that allows users to post YouTube videos. In order to make the video content responsive, I need to add the class "video-container" around any "iframe" tags inserted when users paste a YouTube link ...

Tips on incorporating CKEditor4 wiris MathML formulas into react JS

I am having trouble displaying MathML in the DOM. When I try to render it, the output is not showing correctly in the Editor. I am utilizing CKEditor4 Let me share the code below to provide more context on what I have attempted so far App.js file: impo ...

An error has occurred: Unable to access the 'submit' property as it is undefined

When I inspect my website in Chrome, this is the HTML code that appears: <html> <head> <title>Please Wait</title> <link rel="shortcut icon" href="images/ajax-loader1.gif" type="image/x-icon"> < ...

I am looking to understand how to execute basic PHP scripts using jQuery/AJAX

Due to the size of my actual example being too large, I have created a brief version: example1.php <!DOCTYPE html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <!--jQuery--> <body&g ...

Ways to verify if JSON.parse fails or yields a falsy outcome

Objective: const jsonData = JSON.parse(this.description) ? JSON.parse(this.description) : null When executing the above statement, my aim is to have the ability to parse a value successfully and return null if parsing fails. However, instead of achieving ...

AngularJS: Implementing bidirectional data binding between two separate controllers using a common service

I'm currently working on establishing a two-way data binding connection between two separate controllers and a shared service in AngularJS: app.factory("sharedScope", function($rootScope) { var scope = $rootScope.$new(true); scope.data = "ini ...

Guidelines for naming classes in scss when working with Next.js

Is it possible to use CSS naming conventions in SCSS files with Next.js and then import them into JavaScript using a different convention? // login.module.scss file: .login-button { // some scss styling } // Login.js file: import styles from './ ...

What is the purpose of the hidden field "ufprt" being included in the Razor Umbraco Form?

I am working with a form that is posted to an Umbraco surface controller. Below is the code snippet: @using (Html.BeginUmbracoForm("AddToBasket", "Basket")) { <h1>@Model.productSelectionModel.Product.Title - @Model.productSelectionModel.Product.Pri ...

CodeForge - A major issue with excessively lengthy words resulting in an incorrect solution on assessment 1, but successful execution on my personal computer

Can someone help me understand, why Codeforces is showing an error while the code runs perfectly on my PC? Any assistance in solving this issue would be appreciated. I have included the complete code snippet below for reference. I have also updated it ...

Problem encountered when trying to automatically fill a dropdown list in a custom user registration form in Django

Custom user registration form has been created in Django with the following fields: class RegistrationForm(UserCreationForm): state = forms.ModelChoiceField(State.objects.all()) booth = forms.ModelChoiceField(Booth.objects.none()) first_na ...

What is the method for incorporating a fixed tooltip on a plotline in highstock?

After coming across this example on jsfiddle, I stumbled upon a related question on Highcharts plotband tooltip styling on Stack Overflow... My goal is to have the label displayed from the start without needing the "mouseout and mouseover" events. events ...

Struggling to achieve improved results with Ambient Occlusion in three.js

After reviewing the demonstration here . var depthShader = THREE.ShaderLib[ "depthRGBA" ]; var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vert ...