0

I recently saw a tutorial to upload some photos from here [https://aguacatelang.wordpress.com/2012/08/19/android-multipart-upload-to-node-js/][1]

I've just learned nodejs and less understanding of the structure of programming languages, I found a mistake like this :

home/je/Documents/BE/UploadFoto/app.js:12
var db = new Db('photos', new dbServer('localhost', dbConnection.'27017', {}))
                                                                 ^^^^^^^
SyntaxError: Unexpected string
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:935:3

this is original source code :

var express = require('express');

var app = express()

var fs = require('fs');
var im = require('imagemagick');

var Db = require('mongodb').Db;
var dbServer = require('mongodb').Server;
var dbConnection = require('mongodb').Connection;

var db = new Db('photos', new dbServer('localhost', dbConnection.'DEFAULT_PORT', {}));
db.open(function(err, db){});

app.use(express.bodyParser())

app.get('/', function(req, res){
    res.send(
        '<form action="/upload" method="post" enctype="multipart/form-data">'+
        '<input type="file" name="source">'+
        '<input type="submit" value="Upload">'+
        '</form>'
    );
});

app.post('/upload', function(req, res){
    console.log("Received file:\n" + JSON.stringify(req.files));

    var photoDir = __dirname+"/photos/";
    var thumbnailsDir = __dirname+"/photos/thumbnails/";
    var photoName = req.files.source.name;

    fs.rename(
        req.files.source.path,
        photoDir+photoName,
        function(err){
            if(err != null){
                console.log(err)
                res.send({error:"Server Writting No Good"});
            } else {
                im.resize(
                    {
                        srcData:fs.readFileSync(photoDir+photoName, 'binary'),
                        width:256
                    }, 
                    function(err, stdout, stderr){
                        if(err != null){
                            console.log('stdout : '+stdout)

                            res.send({error:"Resizeing No Good"});
                        } else {
                            //console.log('ELSE stdout : '+stdout)
                            fs.writeFileSync(thumbnailsDir+"thumb_"+photoName, stdout, 'binary');
                            res.send("Ok");
                        }
                    }
                );
            }
        }
    );
});

app.get('/info', function(req, res){
    console.log(__dirname);
    res.send("ok");
});

app.listen(8000);
console.log('connected to localhost....')

I switched DEFAULT_PORT to 27017 because in my PC the port that is used mongodb:localhost/27017. May someone help me? thanks

1
  • What version of express are you using? As you can see here expressjs.com/guide/migrating-4.html#core-changes the structure on Express 4.x changed and BodyParser is no longer part of express. It needs to be added separately.. Commented May 2, 2015 at 19:51

2 Answers 2

2

BodyParser no longer supports parsing multypart requests. You should try using one of these modules.

Here is a simple example using multiparty:

 var multipart = require('multiparty');

 app.post('/upload', function(req, res){

    var form = new multipart.Form();

    form.parse(req, function(err, fields, files) {   
       console.log(files);//list all files uploaded 
       //put in here all the logic applied to your files.        
  }); 
  return;
});

Or you can use it as a middleware, like this:

var multipart = require('connect-multiparty');

app.use(multipart());

app.post('/upload', function(req, res) {
     console.log(req.files);//list all files uploaded
     // apply all logic here
});
Sign up to request clarification or add additional context in comments.

2 Comments

What do you meen by saying source code? Source code of what?
how can you handle multiple images or files in multer ? any idea @ Yaki?
0

I am sending files like Audios,Images and videos etc from Android Using Retrofit ,At server side i am using node.js .

on btnUpload click i am uploading my files to server .

btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(MusicActivity.this, ""+ commonAdapter.getSelectedItems().size(), Toast.LENGTH_SHORT).show();

                String fileUri=null;
                File file=null;
                RequestBody requestFile=null;
                MultipartBody.Part part=null;
                ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);


                for(int i=0;i<commonAdapter.getSelectedItems().size();i++)
                {
                    fileUri = commonAdapter.getSelectedItems().get(i);

                    file = new File(fileUri);

                    requestFile = RequestBody.create(MediaType.parse(fileUri), file);

      //music name must be same as music at node.js , 
      //if its different then it will not worked.
                    part = MultipartBody.Part.createFormData("music", file.getName(), requestFile);

                    Call<UploadObject> myResponseCall = apiService.uploadMusic(part);
                    myResponseCall.enqueue(new Callback<UploadObject>() {
                        @Override
                        public void onResponse(Call<UploadObject> call, Response<UploadObject> response) {
                            Log.d("kkkk","ok response");
                        }

                        @Override
                        public void onFailure(Call<UploadObject> call, Throwable t) {
                            // Toast.makeText(ImagesActivity.this, "Error Occured ! ", Toast.LENGTH_LONG).show();
                            Log.d("kkkk","on failed");
                        }
                    });
                }
            }
        });

My ApiInterface for Retrofit

public interface ApiInterface {
    @Multipart
    @POST("api/uploadImage")
    Call<UploadObject> uploadImage(@Part MultipartBody.Part file);

    @Multipart
    @POST("api/uploadVideo")
    Call<UploadObject> uploadVideo(@Part MultipartBody.Part file);

    @Multipart
    @POST("api/uploadMusic")
    Call<UploadObject> uploadMusic(@Part MultipartBody.Part file);
}

Its my getSelectedItem :- which return selected Items

 public ArrayList<String> getSelectedItems()
    {
        return selectedItems;
    }

At Node.js I am using multer

var express = require('express')
//const bodyParser  = require('body-parser');
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })
var fs = require('fs');

var app = express()

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

app.post('/api/uploadImage', upload.single('image'), function (req, res, next) {

    var tmp_path = req.file.path;

    var target_path = 'uploads/' + req.file.originalname;

    /** A better way to copy the uploaded file. **/
    var src = fs.createReadStream(tmp_path);
    var dest = fs.createWriteStream(target_path);
    src.pipe(dest);
    src.on('end', function() { console.log('complete') });
    src.on('error', function(err) { console.log('error'); });
    fs.unlink(tmp_path);
});

app.post('/api/uploadVideo', upload.single('video'), function (req, res, next) {

    var tmp_path = req.file.path;

    var target_path = 'uploads/' + req.file.originalname;

    /** A better way to copy the uploaded file. **/
    var src = fs.createReadStream(tmp_path);
    var dest = fs.createWriteStream(target_path);
    src.pipe(dest);
    src.on('end', function() { console.log('complete') });
    src.on('error', function(err) { console.log('error'); });
    fs.unlink(tmp_path);
});

app.post('/api/uploadMusic', upload.single('music'), function (req, res, next) {
    var tmp_path = req.file.path;

    var target_path = 'uploads/' + req.file.originalname;

    /** A better way to copy the uploaded file. **/
    var src = fs.createReadStream(tmp_path);
    var dest = fs.createWriteStream(target_path);
    src.pipe(dest);
    src.on('end', function() { console.log('complete') });
    src.on('error', function(err) { console.log('error'); });
    fs.unlink(tmp_path);
});

app.listen(8080,(res,err)=>{
  if(err)
    console.log('error occured while connecting port');
  else
    console.log('Server is Up');
});

I hope its help You!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.