Upload multiple files from input via mouse click only in browser [duplicate]

I am trying so implement web solution where the client can upload multiple files from an <input type="file" /> field.

The problem is that I don’t want to click on the ‘Browse’ button repeatedly to select multiple files one by one.

I want when I click on Browse button and open window pops-up to be able to select multiple file with mouse click only.

My OS is Windows. I tried with KeyboardEvent and MouseEvent and then dispatchEvent.

JS code

Then I tried with the FilePond librarym but it didn’t work.

Finally I propted chatGPT and it said that

answer

So is it really impossible to multi-select files via mouse click (no Ctrl nor Shift pressed) in browsers?

how fix that problème in this case

What this error

Unhandled Runtime Error
TypeError: Failed to construct ‘Image’: Please use the ‘new’ operator, this DOM object constructor cannot be called as a function.

Call Stack
renderWithHooks
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (10649:0)
mountIndeterminateComponent

run this code outpute error

Google Sheets Script: Sum a number of range values; process and add to array

I’m attempting to create a Simple Moving Average (SMA) for an existing list of downloaded ETH prices. The main function calls a separate function to do the SMA calculation.

It has 2 params:
sheet: A ‘sheet’ object
sma1: The length of rows to do the calc on – 12 in this example.

The function:

function calcParams(sheet, sma1) {
  if (sheet === null) return false;

  var dPrices = sheet.getRange('B6:B8642').getValues();
  var len = dPrices.length;

  var sum = 0;
  var values = [];
  for (let i = 0; i < len; i++) {
    if (i < (sma1 - 1) ) {
      values[i] = "";
    } else {
      for (var j = (i - (sma1 - 1)); j = i; j++) {
        sum += dPrices[j];
      }
      values[i] = round(sum/sma1, 2);
    }
  }
  var dSMA1 = sheet.getRange('C6:C8642').setValues(values);
}

While the ‘For’ goes through the first 11 iterations, there is not enough data to sum 12 values to get the average, so the values array saves a blank.

On the 12th iteration, the code is trying to get 11 previous values from dPrices plus the current one, to sum. This sum is divided by 12 for the SMA, and added to the values array.

From debugging, it appears that the var j is “stuck” at 11, whereas it should iterate from 0 to 11. As a JavaScript novice I can’t seem to ID where my code is wrong, so any suggestions would be appreciated.

Blob not found “sometimes” when accessing a content URI subsequent times

we are currently facing an issue when working with blobs in our application. We organize attachments in our application with blob/content URIs. The general flow is as follows:

  • We use XMLHttpRequest to fetch a binary from our backend
  • After having fully received the binary, we use URL.createObjectURL to create a content URI to the attachment (e.g. content://com.gaia.blob/d7809c88-a0e7-4fe6-b049-68d9154d8794?offset=0&size=59301)
  • We then feed this URL to a component that is responsible for displaying the binary (Like react-native’s Image component)

Due to the architecture of our application, we never use external URLs for attachments (like https://path/to/image.png). Our client accesses a known URL for an attachment (like https://path/to/attachment/<id> (using XMLHttpRequest explained above), which will return the binary directly, we create a content URI for it and manage it using said URL. This works very well for the web version of our application (which uses react, not react-native), but in RN, we’re facing some issues.

The procedure described above works without a problem on RN, we get a content URI and can feed it to a component to display it, with no problem. In some scenarios, we need to access the content URI again after we have already displayed it (meaning fed it to e.g. Image), for example for various actions regarding the attachment (Download, which just copies the attachment to the downloads folder, Open with, Share and so on).
At some point after initially displaying the attachment and trying to access the content uri again, the binary data of the attachment is gone. It reports

[13:22:21.245Z][Console] [java.io.FileNotFoundException: Cannot open content://com.gaia.blob/d7809c88-a0e7-4fe6-b049-68d9154d8794?offset=0&size=59301, blob not found.] 

The difficult part is that we don’t know what we do in between that breaks things. The user may click on a button, which renders a view, or a bottom sheet or something else, goes to another screen, comes back, tries to open the previously displayed attachment using their default application, and it’s broken.

To add to this, it doesn’t happen every time. We have been unable to set up a scenario that reproduces this bug consistently. Sometimes accessing the attachment after the user opened a bottom sheet (note: This bug isn’t related to us opening a bottom sheet, we have the same problem everywhere we interact with attachments, this is just an example) and closing it again will work for 2, 3 times, and then it breaks, sometimes it breaks right away.

I’m sorry I’m being vague here and can’t describe the issue any further, but we simply don’t know what we’re doing between invoking createObjectURL and the error mentioned above. Unfortunately, the project is closed source so I can not provide a working example to test this.

In the web version of our application, we use revokeObjectURL (at a point when we are sure we don’t need the binary anymore). However, due to revokeObjectURL not being implemented in RN, we obviously don’t do this here.

My gut tells me, that the binary is getting garbage collected. After looking through the RN’s code base, I noticed that the close function in react-native/Libraries/Blob/Blob.js:135 does exactly that. However, I added a log entry to it and verified that it’s never getting called throughout this process.

What we sometimes see in log cat are warnings like

2024-11-19 13:58:32.739 12664-12672 System                  com.gaia                             W  A resource failed to call close. 

Although we’re not sure whether or not they are related.

Again, I’m sorry to not be able to provide further information. I’d be happy to give additional feedback if needed. If individual pieces of code are needed, I may be able to provide them, unfortunately, due to the project not being public, I can’t provide a reproducible example. I guess to have some foundation for a discussion:

  • Is there any way to check if the binary is being garbage collected by hermes?
  • Can one tweak the GC behavior in any way (when to gc what)?

Again, we’re not even sure GC is the problem here, but it’s the only thing we can think of as of now.

We are currently running 0.75.2, due to some dependencies, we’re currently unable to update to a later version. It’s also unknown for how long this problem has existed, we first noticed it two weeks ago.

Wait for multiple times axios access finished

I have script like this below.

It start multiple API access.

    var temp = [];
    for (let i = 0; i < `10;i++){
        var url = `http://www.myapi.com/api/?id=${i}`;
        axios.get(url).then(res =>{
            temp[i] = res['data'];
            //I want to do something if every API get the results.
            }).catch(res => {
            console.log("axios error");
        });
    }
    

Now I want to wait every 10 api access finished.

Is it possible or how can I do this?

Nestjs No Encryption For Database Provider

i am working on a project in nestjs and I am trying to connect to my db but I keep getting no encryption error

This is my Database Provider

export const DataBaseProviders = [
  {
    provide: REPOSITORY_KEYS.DATA_SOURCE,
    useFactory: async (configService: ConfigService) => {
      const dataSource = new DataSource({
        type: configService.get<DB_TYPE>('DB_TYPE') as DB_TYPE,
        host: configService.get<string>('DB_HOST'),
        port: configService.get<number>('DB_PORT'),
        username: configService.get<string>('DB_USERNAME'),
        password: configService.get<string>('DB_PASSWORD'),
        database: configService.get<string>('DB_NAME'),
        entities: [__dirname + '/../**/*.entity{.ts,.js}'],
        synchronize:
          configService.get<string>('NODE_ENV') == 'production' ? false : true,
      });
      return dataSource.initialize();
    },
    inject: [ConfigService],
  },
];
 

This is the content of my .env

DB_TYPE="--"
DB_HOST="--"
DB_PORT=--
DB_USERNAME="--"
DB_PASSWORD="--"
DB_NAME="--"

This is the error ( Note : I have edited the db credential in the error message like the IP )

[Nest] 12584 – 11/20/2024, 11:37:30 AM ERROR [ExceptionHandler] no pg_hba.conf entry for host “000.00.00.00”, user “admin”, database “mydb”, no encryption
error: no pg_hba.conf entry for host “000.00.00.00”, user “admin”, database “mydb”, no encryption

How to make Column group expand/collapse work in AgGrid?

I have an AgGrid configured with the following column definitions:

const colDefs = ref([
  {
    field: "make"
  },
  { field: "model" },
  {
    headerName: "Col Group",
    columnGroupShow: "open",
    children: [{ field: "price" }, { field: "electric" }],
  },
]);

As you can see, I have configured a column group named “Col Group” and according to AgGrid documentation, there should be an option to collapse and expand the group, but I don’t see it in my grid.

Here’s a working example

Am I missing something or doing something wrong? How can I have the collapse/expand options working for this column group?

stanza.js xmpp +esm cdn typeError

I am having issues with connecting to my Prosody server using the stanza +esm cdn dist.

The websocket connection works with a standard WebSocket object connection in the HTML file (see first script) however the second script using Stanza cdn errors.

The wss connection works fine with stanza package in a node script. I just can’t get it to work with cdn ESM link in a standard, standalone HTML file. Any assistance would be appreciated.

Connection error: TypeError: Cannot read properties of undefined (reading ‘call’)

at new ti (_stream_duplex.js:58:14)
at new Oh (websocket.js:9:9)
at Kh.connect (Client.js:300:31)
at index.html:22:16

HTML file:

<html>
<head>
    <title>Stanza.js +ESM</title>
</head>
<body>
    <script>
    // this works
        const socket = new WebSocket('wss://test.com:5281/xmpp-websocket', 'xmpp');
        socket.onopen = () => console.log('Connected!');
        socket.onerror = (err) => console.error('WebSocket Error:', err);
    </script>
     <script type="module">
    // this errors
        import * as stanza from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm'

        const client = stanza.createClient({
            jid: '[email protected]',
            password: 'password',
            resource: 'web',
            transports: {
                websocket: 'wss://test.com:5281/xmpp-websocket'
            }
        });

        console.log(client);
        console.log(client.config);

        client.on('session:started', () => {
            console.log('Stanza Connected');
            client.getRoster();
            client.sendPresence();
        });

        client.on('chat', msg => {
            console.log('Received chat:', msg);
        });

        client.connect().catch(err => {
            console.error('Connection error:', err);
        });

        client.on('connected', () => console.log('Connected to XMPP server'));

        function sendMessage() {
            client.sendMessage({
                to: '[email protected]',
                body: 'Hello from Stanza WEB!',
                type: 'chat'
            });
        }
    </script>
</body>
</html>```

Getting not authorised error while run the here maps api key

I have created API key from here.com
key generated and test is also working as intended.
but while creating a function based on API key, I am getting “cause” : “App mnTrY8NvPwu6nt8h8AR6 credentials do not authorize access to per… (use muteHttpExceptions option to examine full response)” error.

function getParkingDetails2(location) {
try {
// Step 1: Get coordinates for the location
const geocodeUrl = `https://geocode.search.hereapi.com/v1/geocode? 
q=${encodeURIComponent(location)}&apiKey=${HERE_API_KEY}`;
const geocodeResponse = UrlFetchApp.fetch(geocodeUrl);
const geocodeData = JSON.parse(geocodeResponse.getContentText());

if (!geocodeData.items || geocodeData.items.length === 0) {
  return { error: `No coordinates found for location: ${location}` };
}

const { lat, lng } = geocodeData.items[0].position;

// Step 2: Define a bounding box around the coordinates
const delta = 0.05; // Adjust for search area size
const bbox = `${lat + delta},${lng - delta},${lat - delta},${lng + delta}`;

// Step 3: Fetch parking details using HERE Parking API
const parkingUrl = `https://osp.cc.api.here.com/parking/segments? 
bbox=${bbox}&apiKey=${HERE_API_KEY}`;
const parkingResponse = UrlFetchApp.fetch(parkingUrl);
const parkingData = JSON.parse(parkingResponse.getContentText());

if (!parkingData || parkingData.length === 0) {
  return { error: `No parking data found near ${location}` };
}

return { parkingSegments: parkingData };
 } catch (error) {
Logger.log('Error fetching parking details: ' + error.message);
return { error: 'An unexpected error occurred while retrieving parking data' };
  }
}

function testGetParkingDetails() {
const location = 'Washington';
const parkingDetails = getParkingDetails2(location);
Logger.log(parkingDetails);
}

Can someone help on it please

Implement oAuth 1.0 in ky + react-query

I want to implement oAuth 1.0 in ky, here is my code(s):

export const wooApiV3 = ky.extend({
  headers: {
    Accept: "application/json",
  },
  hooks: {
    beforeRequest: [
      (request, options) => {
        const extendedOptions = options as ExtendedOptions;
        const url = new URL(request.url, extendedOptions.prefixUrl);
        const existingParams = new URLSearchParams(url.searchParams);
        
        const oauthParams: Record<string, string> = {
          oauth_consumer_key: process.env.CUSTOMER_KEY!,
          oauth_nonce: generateNonce(),
          oauth_signature_method: 'HMAC-SHA1',
          oauth_timestamp: generateTimestamp().toString(),
          oauth_version: '1.0',
        };
        for (const [key, value] of Object.entries(oauthParams)) {
          existingParams.set(key, value);
        }
        const signature = generateOAuthSignature(
          request.method || 'GET',
          url.origin + url.pathname,
          Object.fromEntries(existingParams),
          process.env.CUSTOMER_SECRET!
        );
        existingParams.set('oauth_signature', signature);
        extendedOptions.searchParams = existingParams;
      },
    ]
  },
  prefixUrl: wooPrefixUrl,
});

Helpers function(s):

import CryptoJS from 'crypto-js';

export const generateNonce = (): string => Math.random().toString(36).slice(2, 15);
export const generateTimestamp = (): number => Math.floor(Date.now() / 1000);

export const generateOAuthSignature = (
  method: string,
  url: string,
  params: Record<string, string>,
  consumerSecret: string
): string => {
  const sortedParams = Object.keys(params)
    .sort()
    .map(
      key =>
        `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
    )
    .join('&');
  const baseString = [
    method.toUpperCase(),
    encodeURIComponent(url),
    encodeURIComponent(sortedParams),
  ].join('&');

  const signingKey = `${encodeURIComponent(consumerSecret)}&`;
  const hash = CryptoJS.HmacSHA1(baseString, signingKey);
  return CryptoJS.enc.Base64.stringify(hash);
};

Same functionality from Postman is working, but in combination with @tanstack/react-query data is always undefined.

import { wooApiV3 } from "@/services/instance";
import { productSchema } from "./schema";

export const ProductServices = {
  fetchAll: async () => {
    const response = await wooApiV3.get(`products`).json();
    return productSchema.parse(response);
  },
};

Woo response without oAuth:

{
    "code": "woocommerce_rest_cannot_view",
    "message": "Sorry, you cannot list resources.",
    "data": {
        "status": 401
    }
}

Woo response with oAuth:

[] - array of products, status code 200

What is the problem here? Have a nice day!

How to check if element exist and then do further thing in cypress

I know there are a few questions similar to mine, but I can’t fix my issue with the solutions.

I’m working on a test that adds products to the cart, the logic I want to write is if the item is not out of stock, then click add to cart button,

Here’s my code

describe('Add item to cart', () => {
  it('should be able to add all items into the cart', () => {
    caseData.forEach(item => {
      const url = baseURL + item.url;
      cy.visit(url);
      cy.get(`[data-test-id=${notifyButton}]`).then(element => {
        if (element.length === 0) { // check if the item is not out of stock
          cy.scrollAndClick(`data-test-id=${addToCartButton}`);
        }

      })
    })
  });
})

and I got the error when cypress can not find the element

Timed out retrying after 3000ms: Expected to find element: [data-test-id=notify-me-button], but never found it.

I also tried like element.is(':visible') and also not working

Does anyone know where I may be wrong? Thanks a lot!

Receiving the response from a file upload API

I am building an API endpoint to upload files. The file is successfully uploaded but Axios is returning a CORS network issue while uploading. This is preventing the response from the endpoint to be received.

The code I am using is the following:

const express = require("express");
const app = express();
const cors = require("cors");
const https=require('https');
const fs = require('fs');
const bodyParser = require('body-parser');
const multer = require('multer')
const options = {
    key: fs.readFileSync(
        "/etc/letsencrypt/live/liveslowsailfast.com/privkey.pem"
    ),
    cert: fs.readFileSync(
        "/etc/letsencrypt/live/liveslowsailfast.com/fullchain.pem"
    ),
};

var corsOptions = {
    origin: ["https://liveslowsailfast.com"],
    optionsSuccessStatus: 200, // For legacy browser support
    credentials: true,
};

app.use(cors(corsOptions));

app.use(express.json());
//app.use(express.urlencoded({ extended: true }));

global.__basedir = __dirname;

const initRoutes = require("./routes");

//app.use(bodyParser.urlencoded());

//app.use(bodyParser.json());
//app.use(express.urlencoded({ extended: true }));
initRoutes(app);



const maxSize = 2 * 1024 * 1024;

let storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, __basedir + "/uploads/gantt");
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  },
});
const upload = multer({
    storage: storage,
    limits: { fileSize: maxSize },
});

function uploadMiddleware(req, res, next) {
    try {
        upload.single('file')(req, res, function(err) {
            if(err) res.status(400).json({status: 'error', message: err.message})
            else next()
        })
    } catch (error) {
        console.log(error);
    }
}
app.post('/api/upload', uploadMiddleware, (req, res) => {
  res.send(200).json('Upload succesfull');
});

let port = 8079;
let portSSL = 8080;
app.listen(port, () => {
  console.log(`Running at localhost:${port}`);
});
https.createServer(options, app).listen(portSSL);

Nothing is thrown in the API console, so I don’t know where to look to understand the issue. The code to call the endpoint is:

function uploadFile(){
    const config = {
        onUploadProgress: function(progressEvent) {
            var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
            console.log(percentCompleted)
        },
    }
    let url = "https://liveslowsailfast.com:8080/api/upload"
    const formData = new FormData(document.getElementById('uploadGantt'));
    axios.post(url, formData, config)
        .then(function(response){
            console.log(response);
        })
        .catch(function (error) {
            console.log('Error', 'An error happened while trying to upload Gantt to server: ' + error, 'warning');
        });
}

I also tried to read error response to see more about the error but I get undefined.

Cloudflare caching behavior regarding index.html file

My origin server is sending Cache-Control: no-store, max-age=0 with my index.html.
Cloudflare has all the defaults untouched(Edge Cache TTL & Browser Cache TTL). But I am getting some feedback from users that app is crashing due to old javascript bundle being requested after release (but not always and not all cleints), which can only happen when old index.html is served or retrieved from browser cache. I can not ask users for the headers they are getting with html.
But I always get the correct Cache-control header with html which tells not to cache the file (no-store)

The question: Is it possible that default cloudflare settings are overriding Cache-control for html ?
But if so I would be facing the same issue after every deploy.

Node JS Sends html as response instead of JSOM

I have a node js app in VPS and static files are served from dist folder (react app build files). However when i make a http request from my client, I get html as response instead of JSON

const express = require("express");
const publicRoute = require("./routes/publicRoute");
const cookieParser = require("cookie-parser");
const privateRoute = require("./routes/privateRoute");
const path = require("path");
const app = express();

app.use(function (req, res, next) {
  const allowedOrigins = process.env.ALLOWED_ORIGINS.split(",");
  const NODE_ENV = process.env.NODE_ENV;

  const origin = req.headers.origin;
 if (origin && allowedOrigins.includes(origin)   ) {
    res.setHeader("Access-Control-Allow-Origin", origin);
  }

  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PUT, DELETE, OPTIONS",
  );
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Content-Type,Authorisation,x-client-type,Accept",
  );
  res.setHeader("Access-Control-Allow-Credentials", "true");
  if (req.method === "OPTIONS") {
    return res.status(200).end();
  }
  next();
});

app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/user", publicRoute); // routes for Login,reset etc
app.use("/private", privateRoute); // private routes for dashboard,profile etc

app.use(express.static(path.join(__dirname, "dist")));
app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "dist", "index.html"));
});

app.get("/test", (req, res) => {
  res.json({ test: true });
});

app.listen(3000, () => console.log("app started on port 3000"));

Sample API request from client

axios.get(`https://example.org/[email protected]`, {
withCredentials: true,
}).then((res) => {
console.log(res.data);
})
.catch((e) => {
console.log(e);
});

What am I doing wrong here? When i tried the same setup in development environment there were no issues. I got only JSON as response. But I get HTML response in the Application hosted in VPS