The issue encountered while uploading files using Ionic's native file transfer feature to a Node.js Express server is that the `

I'm new to developing with the ionic framework.

Here's the flow of my ionic app: - Choose an image from folders and click on the "upload a picture" button. - I utilized Ionic Native File Transfer for uploading to a Node.js express server.

This is the code I used:

//Ionic page

//Node.js source

Main Point: app.post('/upload', function(req,res)) , uploadImage()

//ionic3-item.js
      uploadImage()   //When press upload button
      {

          const fileTransfer:FileTransferObject = this.transfer.create();

          let option: FileUploadOptions = {
            fileKey:'file',
            fileName:'name.jpg',
            mimeType:'image/jpeg'
          };
          fileTransfer.upload(this.fileurl, encodeURI("http://192.168.1.249:8080/upload"),option);

      }
    }

    //This is the Node.js server code.      

    //route/index.js
    module.exports = function(app, Article)
    {

        //Uploaded Article------------------This part -------------------------
        app.post('/upload', function(req,res){            
            console.log(req.files);
        });   

    }

However, I'm encountering an issue where req.files is undefined. I am unsure how to handle the uploaded files from the Ionic app. Any assistance would be greatly appreciated.

Thank you.

Answer №1

This section contains the client-side source code.

var name = "upload";  

let option: FileUploadOptions = {
  fileKey:'file',
  mimeType:'audio/3gp',
  httpMethod:'POST',
  fileName:'user_step4#'+name
};

this.loader = this.loadingCtrl.create({



  content:'Logging in...',



 });


this.loader.present();

const fileTransfer:FileTransferObject = this.transfer.create();

console.log('filename'+this.curfilename);

fileTransfer.upload(this.file.externalRootDirectory+this.curfilename, encodeURI(localStorage.getItem('GlobalIP')+"/upload"),option).then((result)=>
{
  console.log('success');
}).catch(error=>{
this.loader.dismiss();      
console.log('uploaderror');
console.log(error.message);  
});   
}

The following code pertains to the server side:

var multer      = require('multer');


var storage = multer.diskStorage({
destination:function(req, file, cb)
{
    console.log('uploadpath:'+file.originalname);

var pathname = file.originalname.split('#');
    console.log(file.originalname);
var path = pathname[0].replace('_','/');


console.log(path);

    cb(null,'public/resources/'+path);

},filename:function(req,file,cb)    
{
   var pathname = file.originalname.split('#');
   var filename = pathname[1];
   console.log(filename);
if(filename!=undefined)
        cb(null, filename);            
}
});


//For multipart/form-data Uploading
var upload = multer({storage:storage});

app.post('/upload',upload.single('file'), function(req,res,next)
{
    console.log("uploaded");
    res.json({result:1});

});

We appreciate your time and attention.

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

How to Capture Clicks on Any DOM Element in React

Currently working on a web project using React and Node. My goal is to monitor all clicks across the entire document and verify if the previous click occurred within a 2-minute timeframe. ...

The expression req.files consistently comes back as an empty [object]

I have been encountering an issue with saving uploaded files using their original names (with express-fileupload). Whenever I upload a file, it gets saved in the directory as [object Object]. Node: var express = require('express') var app = exp ...

Issue with error handling in Node and MongoDB when using Express, Mongoose, and the 'mongoose-unique-validator' plugin

I am facing an issue with the 'mongoose-unique-validator' plugin when trying to handle Mongo ValidationError in my custom error handler. Despite other errors being handled correctly, this specific one is not triggering the desired response from m ...

Utilizing a package from your local computer

Due to my current circumstances, I am unable to utilize the npm publish command to release a package on the internet and subsequently use npm install. I also have no intention of publishing it on a remote server like nexus. Is there a method available to ...

unable to establish connection due to port error in node.js

While executing node app.js I encountered the following error message info - socket.io started warn - error raised: Error: listen EACCES This snippet shows all the JavaScript code within the application. After running sudo supervisor app.js T ...

Utilizing Grunt bake to generate unique files with various content from a single template

Is it possible to use bake to display multiple contents within the same styled template? https://github.com/MathiasPaumgarten/grunt-bake For example, if my template looks like this: <div style="background-color:red"> </div> And I have Cont ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

Is there a method to consistently implement a controller function across all routes within a router file in Express?

I have the following code snippets within an application. I am looking for a way to apply "authController.isLoggedIn" to each instance of "router.get" without having to repeat it multiple times. Initially, I thought using router.use might be the solution ...

Utilize Jade to showcase information within an input field

I'm still learning Jade and am trying to showcase some data as the value in a text input. For example: input(type="text", name="date", value="THISRIGHTHURR") However, I specifically want the value to be set to viewpost.date. I have attempted various ...

Encountering a 404 error when attempting to post from a Node.js express app to a

Trying to post to a MySQL database has been giving me a 404 error. I have searched through various posts here, but none of the accepted solutions seem to work for me. I'm struggling to figure out what I am doing wrong. When utilizing a GET request, t ...

How can I search for collection data that contains a specific string within objects of an array using MongoDB?

In my MongoDB collection, I have multiple records. Each record contains an array with objects that have various fields. Here is the structure of my collection: [{ "name" : "Karthik Thurairaja", "universities" : [ { "name" : " ...

Encountering an error code ELIFECYCLE while trying to run npm dev. Struggling to identify and resolve the issue

While I lack experience with nodeJS, I am currently working on creating some test applications using Plaid. Unfortunately, I keep encountering an error whenever I try to run npm run dev. PS D:\Projects\mern-plaid> npm run dev > <a href ...

How can I retrieve the count array of subdocuments in Mongoose?

I'm trying to retrieve the total number of comments associated with Place models without directly populating the comment field using GET /places. Below is my place model: const placeSchema = mongoose.Schema( { type: { type: String }, engli ...

Encountering difficulties in setting up a Next.js app due to a node_modules/node-sass error

Encountering problems while attempting to set up a new nextjs application due to node_modules/node-sass issue My goal is to create a nextjs app using the command provided in their documentation (npx create-next-app@latest) with specific configurations inc ...

There has been a mistake: The module '.... ode_modules erser-webpack-plugindistindex.js' cannot be found. Please ensure that the package.json file contains a correct "main" entry

After setting up Vue.js and executing npm run serve, I encountered the following error: PS C:\Amit\Demo\VUEDemo\myvue> npm run serve > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f5e1eeedfdd8a8b6 ...

What is the secret behind node.js efficiently managing a high volume of requests simultaneously? Is there any delay for other clients waiting in line

How does node.js manage a large number of requests when the server is already occupied with handling complex operations per request? Do other clients have to wait until the current operation is completed before receiving a response? For instance, in the ...

The Hyperledger Sawtooth JavaScript SDK has encountered invalid submitted batches

I am currently working on integrating a hyperledger sawtooth transaction using the javascript SDK. I am following the tutorial provided here: . /* *Create the transaction header */ const createTransactionHeader = function createTransactionHeader(payloadBy ...

What is the best way to include certain files within a directory on git?

./main ../firstDirectory ../file_A.js ../file_B.js ../file_C.js ../file_D.js ../file_E.js I am attempting to develop a script that selectively adds changes for specific files within a directory, such as file_A, file_C, and file_E. ...

Retrieving detailed information from MongoDB in a Node.js environment

I am currently developing a nodejs server using mongoDB. I have some sample data that looks like this: { "_id": ObjectId("555f1c0c7f4b820758b439b0"), "user": "Guest1", "friend": [{ "myfriend": "Guest2", "in ...

Struggling to successfully update columns in postgresql using knex.js

Encountering a very peculiar issue during updates where I don't receive any response - no errors, warnings, success messages - it's as if nothing is changing. The request seems to be stuck in an infinite loop, always loading. I am using knex.js f ...