Tips for sending a URL in form-data as a file with JavaScript or Axios

Currently, I am using Vue.js and Axios to send form data to a specific link. However, I encountered an issue where the file is not being sent and I am receiving an error message.

The parameter 'file' had the following problems: file transferred without multipart should be base64 encoded

I attempted to resolve this by modifying the data.append('file', url) by adding another parameter like data.append('file', url,{type:'pdf'}). Unfortunately, this resulted in an error stating that the second parameter is not a blob. The root cause of this problem lies in using a URL instead of a file, which cannot be changed as the API documentation requires sending form data with a file. As a workaround, I am trying to replace the file with a live URL.

var data = new FormData();
        var url= 'https://storage.cloudconvert.com/xxxxx.pdf';
        data.append('name','file')
        data.append('filename', 'amjad');
        data.append('file', url);
        data.append('saved', 'true');
        data.append('type', 'pdf');
        axios.post('myapiurl',data, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },

        }).then(res => {
            console.log(res);
        })

Answer №1

Attempt to access the file and then convert it using encoding methods similar to this:

 function getPdf(){
        // Extract text from a specified URL
        var request = new XMLHttpRequest();
        request.open('GET', 'https://storage.cloudconvert.com/xxxxx.pdf', true);
        request.send(null);
        request.onreadystatechange = function () {
            if (request.readyState === 4 && request.status === 200) {
                var type = request.getResponseHeader('Content-Type');
                if (type.indexOf("pdf") !== 1) {
                    return request.responseText;
                }
            }
        }
    }
// Perform String Encoding
    var pdf = btoa(getPdf()); 
    
    
    var data = new FormData();
           
            data.append('name','file')
            data.append('filename', 'amjad');
            data.append('file', pdf);
            data.append('saved', 'true');
            data.append('type', 'pdf');
            axios.post('myapiurl',data, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
    
            }).then(res => {
                console.log(res);
            })

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

I'm always puzzled when the 'if' statement is triggered, regardless of whether

I've encountered an issue with my code where, despite the if statement at the end evaluating to false, the code continues to run and data is still being added to MongoDB. This behavior has left me puzzled as to why it's happening... Even when I ...

Authentication Error (401) in WordPress JWT

Recently, I came across WordPress and started using it. However, I encountered some issues while trying to integrate JWT with a custom endpoint. Despite configuring my API and JWT correctly, I faced an authentication problem during my AJAX request. It&ap ...

Uncaught jQuery onchange event not firing

I am facing an issue with a drop-down list inside a data grid on the main page. When values are changed, a popup should display and the values from the popup need to be sent back to the main page. However, I am having trouble triggering the onchange event. ...

Is there a way to locate a parent class starting from a child class, and subsequently track down another child class from the parent?

I am facing a challenge with multiple tags structured like this: <div class="A"> <div class="B1">...</div> <div class="C1">Hello World!</div> <div class="C2">World Hell ...

Watching a Computed Value in EmberJS

What causes the discrepancy between the two sets of code? Utilizing computed: computed: Ember.computed('selected', function() { console.log('computed'); return this.get('selected'); }), observer1: Ember.observer(&ap ...

React-onclickoutside does not function properly within an iframe

I have developed a custom drop-down list using reactjs. I utilized react-onclickoutside to recognize clicks outside the list and close it. While this method works effectively, it does not respond to clicks within an iframe. import onClickOutside from &apo ...

Troubleshooting Problem with Vue, Laravel, and Axios Integration

Utilizing Vue axios calls to access Laravel API's from localhost Encountered an error in Scenario 1: The 'Access-Control-Allow-Origin' header has multiple values '*, *', only one value allowed Resolved error by adding the follo ...

Implementing momentLocalizer with moment.js in react-big-calendar alongside fullcalendar.js

I'm currently working with react-big-calendar and I require assistance in setting up localization as per the example provided on GitHub. import BigCalendar from 'react-big-calendar'; import moment from 'moment'; BigCalendar.setLo ...

Obtaining the attribute value of a disabled element in an Angular JS application

Currently, I am struggling to retrieve the attribute value of a disabled element during runtime and then assert its value. The code I'm using is not providing the desired result: softAssert.assertFalse(shrSub.nextButton().waitForPresent().getAttribu ...

Encountering the "No injector found for element argument to getTestability" error while navigating between various single page applications

Currently, I am conducting tests on Protractor for a website that is bootstrapping AngularJS manually. Despite the steps continuing to execute, I encounter this error: Error while waiting for Protractor to sync with the page: "[ng:test] no injector found ...

Guide for executing Gulp tasks in a sequence one by one

Here is an example snippet: gulp.task "coffee", -> gulp.src("src/server/**/*.coffee") .pipe(coffee {bare: true}).on("error",gutil.log) .pipe(gulp.dest "bin") gulp.task "clean",-> gulp.src("bin", {read:false}) .pipe c ...

An error occurred while trying to import a module due to an unexpected token

Take a look at this codepen link I encountered an error (line 10 in index.vue) with the following import: import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js"; Any idea what could be causing this issue? All other ...

What is the best way to condense JSON on the back end and then expand it on the front end?

Is there a best practice for compressing large JSON objects being sent between the back-end server (using Flask) and the front-end (Vue JS)? The file size is approximately 35MB, and I'm looking for a way to optimize data transfer in terms of compressi ...

Scheduling tasks for jQuery/Javascript like a Cronjob

I'm currently working on a web application that predominantly uses PHP, however, I am incorporating jQuery/Javascript to retrieve Tweets from users' URLs at http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=. My aim is ...

Received the item back from the database query

When I run the code below; var results = await Promise.all([ database.query("SELECT COUNT(amount) FROM transactions WHERE date >= now() - INTERVAL 1 DAY;"), database.query("SELECT COUNT(amount) FROM transactions WHERE date >= now() - INTER ...

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...

Execute a function before the page reloads in ASP.NET with the help of JQuery

Is there a way to call a function before postback in Asp.Net using JQuery? ...

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

Having trouble getting the waveform to load in IOS Safari when using WavesurferJS in a VueJS application, even though the audio is playing fine

In my VueJS application, I've been facing a challenge with WavesurferJS on IOS Safari for the past week. The issue is that the wavesurfer component cannot fully decode the audio or load the waveform, resulting in just a thin straight line being displa ...

What is causing the bullets for the unordered list to appear before the items are inserted into the list?

Can you explain why the bullets are showing up before the list items are added? <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>To Do List</title> </head> <body> ...