Steps for uploading a file to Google Drive API with a custom name instead of "untitled":

I have attempted to send the name in the object "formData.append" within the code structure, but unfortunately, I have not achieved success.

The documentation states that the name should be sent in the body.

Useful Documentation Links: https://developers.google.com/drive/api/v3/reference/files/create - https://developers.google.com/drive/api/v3/manage-uploads#http_1

Received Response:

{ "kind": "drive#file", "id": "1uz_NN-IyoiPzaheAiKIJu6qlB7ZfxIX2", "name": "Untitled", "mimeType": "application/x-www-form-urlencoded" }

Name: "Untitled"

- Any assistance would be greatly appreciated

Upload.prototype.doUpload = function () {
        var that = this;
        var formData = new FormData();
    
        formData.append("file", this.file);
        formData.append("upload_file", true);
        formData.append("name", "test_file");
    
        $.ajax({
            type: "POST",
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", "Bearer" + " " + localStorage.getItem("accessToken"));
                
            },
            url: "https://www.googleapis.com/upload/drive/v3/files",
            data:{
                uploadType:"multipart"
            },
            success: function (data) {
                console.log(data);
            },
            error: function (error) {
                console.log(error);
            },
            async: true,
            data: formData,
            cache: false,
            processData: false,
            timeout: 60000
        });
    };

Answer №1

Would you consider this revised approach?

Key Modifications:

  • It appears that ajax requests cannot directly handle multipart/form-data using FormData(). Thus, it is necessary to structure the multipart/form-data and send it as the data payload.
    • Currently, your script only uploads the file content without including the file metadata, resulting in the uploaded file lacking a filename. To address this, both the file content and metadata need to be uploaded using multipart/form-data.
  • Your script contains 2 properties under data.

By incorporating the above points into your script, the following modifications can be made.

Revised Script:

Upload.prototype.doUpload = function () {
    const file = this.file;  // Assuming that "this.file" represents the blob.

    const fr = new FileReader();
    fr.readAsDataURL(file);
    fr.onload = function() {
      const boundary = "xxxxxxxxxx";
      let data = "--" + boundary + "\n";
      data += "Content-Type: application/json; charset=UTF-8\n\n";
      data += JSON.stringify({name: "test_file"}) + "\n";
      data += "--" + boundary + "\n";
      data += "Content-Transfer-Encoding: base64\n\n";
      data += fr.result.split(",")[1] + "\n";
      data += "--" + boundary + "--";
      $.ajax({
        type: "POST",
        beforeSend: function(request) {
          request.setRequestHeader("Authorization", "Bearer" + " " + localStorage.getItem("accessToken"));
          request.setRequestHeader("Content-Type", "multipart/related; boundary=" + boundary);
        },
        url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
        success: function (data) {
            console.log(data);
        },
        error: function (error) {
            console.log(error);
        },
        async: true,
        data: data,
        cache: false,
        processData: false,
        timeout: 60000
      });
    }
}

Important Note:

  • In this revised script,
    • It is assumed that this.file in your original script represents the blob.
    • Your access token is required for successful file uploading to Google Drive.
  • When utilizing uploadType=multipart, be mindful that the maximum file size allowed is 5 MB.

Further Resources:

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

The function ajax does not recognize response.forEach as a valid function

When I try to use ajax for fetching data from MySQL using PHP and JavaScript, I encounter a function error stating "response.forEach is not a function". Despite looking through various posts on this issue, none of the suggested solutions have been able to ...

Changing the context results in the entire component being re-rendered

Currently, I am encountering a challenge where I have two different components within my Layout.js component that need to "share" props with each other. To address this issue, I introduced a ContextProvider named IntegrationProvider. However, a new proble ...

Integrate an external script with React and initialize a new instance

I've been working on integrating a neat canvas background feature from this GitHub project into my React web application. Here's what I've attempted: import {WarpSpeed} from './warpspeed.js' import WarpSpeed from './warpspee ...

Creating a dynamic multi-item carousel with Materialize (CSS) cards using data from a loop - here's how!

Using a for loop, the following code generates a list of cards. These cards are intended to be displayed in a carousel with 4 cards visible at once, and a next arrow button allows users to navigate through the next set of 4 cards. Materialize cards have ...

“Unlocking the secret to extracting color from an image in React Native”

While it may sound like a silly question, I am new to the world of React technology. I am looking to extract colors from an image - for example, when a user selects an image to upload, I want to identify all the colors used in that image. If this is possib ...

Troubleshooting PHP echo response issue with AJAX POST and FormData submission

Apologies for the inadequate title, I struggled to come up with a suitable one. Currently, I am working on a web-based platform for movies and anime, where users can contribute to the database by logging in and submitting forms. This project is my first i ...

Setting up Webpack for my typescript React project using Webpack Version 4.39.2

I have been given the task of fixing the Webpack build in a project that I am currently working on. Despite not being an expert in Webpack, I am facing difficulties trying to make it work. The project has an unconventional react frontend with typescript. I ...

What are the different ways to utilize the Angular Loading Bar for specific waiting scenarios?

In the project I am currently working on, navigation is primarily done through Ajax loading of HTML templates. The Angular Loading Bar feature is proving to be quite effective in this setup, as it employs interceptors to keep track of most $http requests. ...

Tips for incorporating a Spinner-GIF ahead of complete loading of ng-include

I'm in the process of dynamically loading HTML partials from the server using a div layer. The template variable is updated when a navigation link is clicked. <div id="ajaxwrapper" ng-include="template"> </div> Everything is functioning ...

Guide to implementing if statements within a map function in JavaScript/Vue.js

Currently, I am developing a small application using Vuejs. In this application, I receive response data and then map it to a variable. However, there are some elements with empty arrays in the data. So, during mapping, I need to check a condition and ma ...

Tips for using jQuery to slowly change a CSS property to "auto"

I've encountered a situation where I have an element styled with position:fixed, and bottom: auto;. When I apply the command .animate({bottom : '10%'});, it smoothly slides to the specified position. However, when I try to set it back to its ...

After refreshing the page in Next JS, there is a delay in loading the Swiper Js styles. The Swiper slides appear stretched while waiting for Next JS to load the styles. Any suggestions

Having an issue with my Next 14.0.3 app and tailwind CSS. I recently installed swiper JS version 11.0.5 using npm. The problem arises when I reload the page, it takes about 1 or 2 seconds for the swiper styles to load. During this time, the swiper slides s ...

Function in React not being successfully passed down between functional components

I have been accustomed to using class components and now I am transitioning into functional components in order to become more proficient with hooks. However, I have encountered an issue where I am struggling to pass a function from one functional compone ...

a dynamic framework that fills out several forms

I am in search of a way to streamline the data entry process for my awards database. Currently, my "people" table consists of five fields: peopleid first middle last display For example, an entry could look like this: peopleid 120 first William middl ...

Hiding validation messages upon clicking in a textbox in ASP.NET MVC: a tutorial

When attempting to hide the validation message on click of the textbox, it remains visible. Can someone please provide assistance? <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @autoco ...

Incorporating an image as a clickable element instead of a traditional button using HTML and

Here's the issue at hand: I currently have "+" and "-" icons at the end of each row to add and delete rows as needed. However, I would like to replace the "-" icon with a trashcan symbol instead. I attempted to do this by replacing it with an image s ...

Is it possible to achieve a smooth transition to the right using CSS

I'm attempting to create a sliding box effect from left to right using only transitions, similar to this: #box { width: 150px; height: 150px; background: red; position:absolute; transition: all 2s ease-out; right:auto; } .active{ bac ...

Dynamic Namespaces in Socket.io is a feature that allows for

I am currently working on implementing multiple namespaces in my app. As I receive route parameters, I dynamically create new namespaces. For example: var nsp = io.of('/'); var className; app.post('/class/:classID',function(req,res){ ...

Is there a way to retrieve random data based on either product id or slug within a single component using useQuery? Currently, all components are displaying the same data

Here is the code I wrote: const fetchCartItem = async () => { if (token) {const {data } = await axios.get(API.GET_PRODUCT_DETAILS_BY_PRODUCT_ID.replace("[ProductID]",item?.ProductID),{headers:{Authorization: token,},});setCartLoading(fal ...

Issue with TypeORM @BeforeInsert causing a field in Entity not to be populated with value

Currently, I am facing an issue where I am attempting to update or insert into a token field before the record is saved. However, when utilizing the @BeforeInsert hook, I encounter the following error: "error": "Cannot read property 'co ...