Estoy intentando utilizar el servicio de almacenamiento de objetos en IBM Bluemix Cloud , pero no puedo enviar imágenes desde mi servidor nodejs. ¿Cómo puedo hacer esto? Sigue mi código de servidor:

unirest
    .post(MY_CONTAINER + new_fname)
    .headers({'Content-Type': 'multipart/form-data', 'X-Auth-Token': token})
    .field({ 'max_file_count': 1 })
    .field({ 'max_file_size': 1 })
    .attach({ 'file': file.originalname, 'relative file': streamFile })
    .end(function (resp) {
            //response
            console.log(resp.status);
            console.log(resp.body);
        });

El principal problema es encontrar la forma correcta de enviar una imagen (png o jpg) al almacenamiento de bluemix usando la API (ya la he subido a nuestro servidor).

2
FelipeCaparelli 26 ene. 2016 a las 06:11

2 respuestas

La mejor respuesta

Usé pkgcloud-bluemix-objectstorage para corregir el error de autenticación de OpenStack que anteriormente usó la v2 y se ha cambiado para usar la v3.

Aquí está el enlace Bluemix - almacenamiento de objetos - node.js - pkgcloud - openstack devuelve 401

El @libik escribe un ejemplo.

var pkgcloud = require('pkgcloud-bluemix-objectstorage');

var fs = require('fs');

// Create a config object
var config = {};
// Specify Openstack as the provider
config.provider = "openstack";
// Authentication url
config.authUrl = 'https://identity.open.softlayer.com/';
config.region= 'dallas';
// Use the service catalog
config.useServiceCatalog = true;
// true for applications running inside Bluemix, otherwise false
config.useInternal = false;
// projectId as provided in your Service Credentials
config.tenantId = '234567890-0987654';
// userId as provided in your Service Credentials
config.userId = '098765434567890';
// username as provided in your Service Credentials
config.username = 'admin_34567890-09876543';
// password as provided in your Service Credentials
config.password = 'sdfghjklkjhgfds';

**//This is part which is NOT in original pkgcloud. This is how it works with newest version of bluemix and pkgcloud at 22.12.2015. 
//In reality, anything you put in this config.auth will be send in body to server, so if you need change anything to make it work, you can. PS : Yes, these are the same credentials as you put to config before. 
//I do not fill this automatically to make it transparent.
config.auth = {
    forceUri  : "https://identity.open.softlayer.com/v3/auth/tokens", //force uri to v3, usually you take the baseurl for authentication and add this to it /v3/auth/tokens (at least in bluemix)    
    interfaceName : "public", //use public for apps outside bluemix and internal for apps inside bluemix. There is also admin interface, I personally do not know, what it is for.
    "identity": {
        "methods": [
            "password"
        ],
        "password": {
            "user": {
                "id": "098765434567890", //userId
                "password": "sdfghjklkjhgfds" //userPassword
            }
        }
    },
    "scope": {
        "project": {
            "id": "234567890-0987654" //projectId
        }
    }
};**

//console.log("config: " + JSON.stringify(config));

// Create a pkgcloud storage client
var storageClient = pkgcloud.storage.createClient(config);


// Authenticate to OpenStack
storageClient.auth(function (error) {
    if (error) {
        console.error("storageClient.auth() : error creating storage client: ", error);
    } else {
        
        //OK
        var new_fname = dir + "__" + file.originalname;
        var readStream = fs.createReadStream('uploads/' + file.filename);
        var writeStream = storageClient.upload({
            container: 'chat-files',
            remote: new_fname
        });

        writeStream.on('error', function(err) {
            // handle your error case
            console.log("concluido o upload com erro!");
            console.log(err);
        });

        writeStream.on('success', function(file) {
            // success, file will be a File model
            console.log("concluido o upload com sucesso!");
        });

        readStream.pipe(writeStream);                
    }
});
5
Community 23 may. 2017 a las 12:25

@JeffSloyer escribió una aplicación de muestra Node.js para cargar archivos en una instancia de Object Storage en Bluemix.

Puedes encontrar el código aquí:

https://github.com/IBM-Bluemix/node-file-upload-swift

El código anterior no puede autenticarse usando Open Stack Swift v3, así que hice una modificación en el módulo skipper-openstack para usar pkgcloud-bluemix-objectstorage:

https://github.com/adasilva70/skipper-openstack.git#adasilva70-patch-1

Clone el repositorio de Jeff y siga las instrucciones del archivo README.md para ejecutar el código. Asegúrese de modificar el archivo package.json con el siguiente para obtener mis cambios:

{
  "name": "node-file-upload-swift",
  "version": "0.0.0",
  "dependencies": {
    "bower": "^1.7.1",
    "cf-deployment-tracker-client": "*",
    "cfenv": "^1.0.3",
    "dotenv": "^1.2.0",
    "express": "~4.x",
    "skipper": "^0.5.8",
    "skipper-openstack": "git+https://github.com/adasilva70/skipper-openstack.git#adasilva70-patch-1",
    "stream": "0.0.2",
    "underscore": "^1.8.3"
  },
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "postinstall": "bower install --allow-root --config.interactive=false"
  }
}
3
Alex da Silva 26 ene. 2016 a las 04:21