Using Google App Engine with Stripe - Enable users to easily upload images for account identity verification directly through their browser using Javascript

After extensive research, I have been exploring how to enable direct browser uploads, particularly in the context of utilizing Stripe with Google App Engine, as discussed on this forum. The Stripe documentation also mentions the possibility of browser uploads here.

Despite my attempts with AJAX, it appears that obtaining the path to a local file is not feasible due to security restrictions. The code snippet below represents the closest progress I have made, but I am struggling to figure out a way to upload an image from the browser without involving the server. The console keeps showing an error message stating "Invalid file: must be uploaded in a multipart/form-data request".

My next step is to experiment with the Jquery Form Plugin, although I am uncertain about the likelihood of success with that approach.

    var formData = new FormData($('#theHTMLForm')[0]);
    var sendarray={purpose:"identity_document", file:formData};
    sendarray=JSON.stringify(sendarray);

            $.ajax({
        type:'POST',
        url: 'https://uploads.stripe.com/v1/files',
        data: sendarray,
        mimeType: "multipart/form-data",
        headers: {
            "Authorization": "Bearer STRIPEPUBLISHABLEKEY"
        },
        contentType: 'application/json',
        processData: false,
        success:function(data){
            alert('success');
            console.log(data);
        },
        error: function(data){
            alert('error');
            console.log(data);
        }
    });

Answer №1

Special thanks to a generous individual on this discussion board who helped me get it functioning properly!! In case anyone else is searching for the same solution, I'll share it here.

Here is the HTML code:

<div>
<form method="post" id="fileinfo" name="fileinfo" ajax="true">
    <input type="file" id="file-box" name="file" required />
    <input type="submit" value="Upload" />
</form>
</div>

<div>
    <div id='label-results'>...</div>
    <pre id="upload-results"></pre>
</div>

And now, the Javascript snippet:

$('#fileinfo').submit(function(event) {
    event.preventDefault();

    var data = new FormData();

    var publishableKey = 'pk_test_***';

    data.append('file', $('#file-box')[0].files[0]);
    data.append('purpose', 'identity_document');

    $.ajax({
        url: 'https://uploads.stripe.com/v1/files',
        data: data,
        headers: {
            'Authorization': 'Bearer ' + publishableKey
        },
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
    }).done(function(data) {
        $('#label-results').text('Success!');
        $('#upload-results').text(JSON.stringify(data, null, 3));
    }).fail(function(response, type, message) {
        $('#label-results').text('Failure: ' + type + ', ' + message);
        $('#upload-results').text(JSON.stringify(response.responseJSON, null, 3));
    });

    return false;
});

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

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

Prevent side-to-side scrolling on elements that exceed the width of the screen

I am working on building a navigation system similar to Google Play, where there are fixed tabs for browsing through the app. I have created a container div that holds various content sections. <div id="container"> <div class="section"> .. ...

What is the best way to change the name of a child object within a clone in three.js? (renaming child objects within clones)

I have designed a 3D model using different elements: ParentObject-001.name = 'ParentObject-001'; ChildObjectA-001.name = 'ChildObjectA-001'; ChildObjectB-001.name = 'ChildObjectB-001'; Then, I combined them with: ParentObject ...

CSS Attribute Selector Wildcard Capture Tool

Suppose I have the following HTML structure: <div class="tocolor-red"> tocolor </div> <div class="tocolor-blue"> tocolor </div> <div class="tocolor-green"> tocolor </div> <div class="tocolor-yellow"> tocolor ...

Sharing properties across various components with Next.js

I'm still getting the hang of using Next.js and encountering issues with sharing data between components. Currently, I have a setup involving three components: //index.js function App() { const choices = [] for (let i = 1; i < 101; i++) { ...

Issue with the loop function

When I try to loop through my code, I keep getting the same "y" value (5) and it doesn't change. What I actually want is to make the ajax call repeat X times [all], passing both the response and the current call number through an anonymous function. A ...

Display a message if the local storage is empty

Recently, I came across a javascript code snippet that is designed to save birthday data in local storage and then display the data within a div element. The current functionality only shows nothing if the storage is empty. However, I require it to display ...

Guide to making an `Ajax Login` button

I am interested in creating a SIGN IN button using ajax. Specifically, I want it to display something (such as welcome) on the same page without refreshing it. This is the progress I have made so far: update2: <form id="myForm" onsubmit="return signi ...

Utilize Content Delivery Network Components in Conjunction with a Command Line Interface Build

As we progress in building our Vue applications, we have been using the standard script tag include method for Vue. However, as we transition from jQuery/Knockout-heavy apps to more complex ones, the maintenance issues that may arise if we don't switc ...

Top method for centering a flexible SVG vertically once the page width becomes too narrow

Currently, I have two SVG images displayed side by side on a webpage. One SVG needs to maintain a fixed size while the other should scale as needed, and I have achieved this functionality. However, I am facing an issue where I want the two SVGs to align v ...

Is there a way to simulate a KeyboardEvent (DOM_VK_UP) that the browser will process as if it were actually pressed by the user?

Take a look at this code snippet inspired by this solution. <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <script> $(this). ...

Is there any way to remove the two default aspNetHidden Divs in asp.net web forms?

After creating an empty webform page in asp.net, the generated code looks like this: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Threetier.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org ...

Using Regular Expressions in Javascript

I have gone through numerous posts with this title, but so far, none of them have addressed my specific query... My requirement is to utilize regex in the following format: "/^ user provided input $/i". The user can include the special regex character * e ...

Strategies for managing the result of findElements?

Snippet A resultsBoard.findElements(By.css(mySelector)).then(function(elements) { elements.forEach(function(val, idx) { elements[idx].getText().then(function(text) { console.log(text); }); }); }); Snippet B resultsBoard.findElements( ...

Having trouble with the jQuery function not working as expected? Can't seem to identify any errors in the code?

I'm attempting to capture the essence of moving clouds from this beautiful theme: (I purchased it on themeforest, but it's originally designed for tumblr) Now, I want to incorporate it into my wordpress website here: The code used to be under ...

Manipulate MySQL data in Node.js by storing it in a variable

Struggling to grasp the concepts of nodeJS/typescript and how to effectively save database query results into variables for return. Seeking assistance to solve the problem faced: Here is a method snippet that needs help: public getAllProducts(): ProductA ...

another solution instead of using several try-catch blocks within a function

Consider a scenario where we define a function as shown below: async function doSomethingWithFriends() { let user, friends, friendsOfFriends = null; try { user = await getUser(); } catch(err){ return [401, err] } try { ...

Populate Select2 with data after making an AJAX call for insertion

Currently, I am implementing the Select2 plugin with AJAX functionality using the code snippet below: $(".select2-ajax").select2({ placeholder: "Search user", minimumInputLength: 1, ajax: { url: $('#url-search-clie ...

React.js and Visual Studio Code have recently been causing unexpected and massive "Module not found" errors

Everything was going smoothly with my project until I uploaded it to Github and then cloned it. Suddenly, I started encountering various "Module not found: Can't resolve..." import errors. For example: Module not found: Can't resolve './co ...