1

I have a really quick question:

I have an img tag (in my template file) that holds an image and in my Angular Controller I call:

var image = document.getElementById('srcImage');

I want to send this image ^ to the backend (I am using REST). The url I would use for this POST method is: '/api/v1/images/addImage'

I've tried ng-file-upload and $http.post, but nothing seems to be working. Is there any way that I can simply send this image over to the server so I can store it in a database or file system? I am open to any solutions to making this happen.

Thanks!!

Zain
  • 21
  • 2
  • 6
  • I'm not posting as answer cause I had the same issue and did a work around... What I did was using Cloudinary, I uploaded the image and then sent the link using Post which i stored at the Db. I know the right way is to convert it to byte stream and send it via Post then work with the image. I'll keep an eye on this as this is something i tried doing and failed. – Alan Aug 05 '16 at 15:58
  • Hey Alan, thanks for answering. Do you know how to convert it to a byte stream and store it? I tried converting to base64 but I've been at this for days with no positive results. Thanks. – Zain Aug 05 '16 at 16:00
  • See: http://stackoverflow.com/a/10755011 – mscdex Aug 05 '16 at 16:02
  • @Zain Can you elaborate on what you're trying to do? It sounds like you're serving a page with an image on it that you then want to send to a REST api you don't control. It seems like an odd case, I just want to make sure we're not missing a simpler or more standard approach to the real problem. – Mic Aug 05 '16 at 16:12
  • @Mic Hey thanks for the reply. I created the REST api with node and all I want to do is send the image that's in my template file to send over to the server. I was able to use ng-file-upload but req.file or req.files on the server side of the POST request were undefined. – Zain Aug 05 '16 at 16:15
  • @Zain I take it you're not serving the image to the client from the same server then. A couple follow-up questions - are you using a server-side web framework on top of node (i.e. ExpressJs, Hapi, etc)? And is the srcImage element a file element? – Mic Aug 05 '16 at 16:56
  • @Mic No, the image is being served locally (from an img folder). I am using express as a Node framework. I just want to send it over to the server and let the server either store the img in a database OR in a file system like GridFS. Also the image is in a tag. Does it need to be in an tag for transferring it over to the server? – Zain Aug 05 '16 at 17:23
  • @Zain Understood. I'm not sure it's impossible to do it in an image tag, but I certainly think you will find it easier if you use an input with type="file". Try getting it working that way first, and then if you want to get fancier you can hide the input (there are some caveats with this) and show an img element. Also, I second the recommendation for using the multer express middleware for the server-side handling. I've used it for my file uploads in express apps before. – Mic Aug 05 '16 at 17:32
  • @Mic Awesome, thanks. The plan is to use this in the Ionic Framework (where I can take a photo) and send it off to the server. Do you know how to do that? Thanks. Also with the input would it be like this: ? – Zain Aug 05 '16 at 17:34
  • I haven't used the Ionic Framework. There's nothing magical here though, your goal is to generate an HTTP request with the correct headers and payload. Something like this might help: http://stackoverflow.com/questions/30534820/ionic-app-image-upload-from-camera-photo-library – Mic Aug 05 '16 at 17:48
  • Perfect, thanks for all the help. – Zain Aug 05 '16 at 17:50

2 Answers2

2

You can use below libraries, they have good documentation also

For Frontend - https://github.com/nervgh/angular-file-upload

For Backend - https://github.com/expressjs/multer

Sample Snippet -

In HTML :

<input type="file" nv-file-select="" uploader="ctrl.uploader" multiple />

Angular Controller :

vm.uploader = new FileUploader({
    url: 'http://' + SERVER_URL + '/upload',
    formData: [{
        id: 1
    }]
});

vm.save = function() {
    vm.uploader.onBeforeUploadItem = function (item) {
        console.log(item);
        /* some action */
    };

    vm.uploader.onSuccessItem = function (item, imgResponse, status, headers) {
        console.log(item);
        console.log(imgResponse);
        console.log(status);
        console.log(headers);
        /* some action */
    };
};

Node Server :

var fs = require('fs');
var multer = require('multer');

var fileName = '';
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        var dirPath = 'path/to/save/file'
        if (!fs.existsSync(dirPath)) {
            var dir = fs.mkdirSync(dirPath);
        }
        cb(null, dirPath + '/');
    },
    filename: function (req, file, cb) {
        var ext = file.originalname.substring(file.originalname.lastIndexOf("."));
        fileName = Date.now() + ext;
        cb(null, fileName);
    }
});

// Assuming Express -
app.get('/upload', function (req, res) {
    var upload = multer({
        storage: storage
    }).array('file', 12);

    upload(req, res, function (err) {
        if (err) {
            // An error occurred when uploading
            res.json(err);
        }
        res.json(fileName);
    });
});
Aks1357
  • 1,062
  • 1
  • 9
  • 19
0

You can try multipart/form-data like this:

<form id       =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/photo"
     method    =  "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>
wahwahwah
  • 3,254
  • 1
  • 21
  • 40
Rohit Shedage
  • 23,944
  • 1
  • 13
  • 18
  • So if I want to grab an image using "document.getElementByID( '..' )", then do I have to make sure the "enctype" in the img tag is set to "multipart/form-data" ? Because right now, I was able to use ng-file-upload and in my Node.js script (POST), req.body is present but req.files or req.file is not, so I was wondering if not setting "enctype" had anything to do with it? – Zain Aug 05 '16 at 16:13
  • Okay great, I will try that later today and hopefully it works! – Zain Aug 05 '16 at 16:17
  • @RohitShedage don't write answers with just links. When the links die, the post becomes useless. Instead try to summarise the contents of the link in your post. http://stackoverflow.com/help/how-to-answer – Iceman Aug 05 '16 at 20:30