I'm trying to retrieve a picture from my API, I'm sending the data like this :
router.post('/loadpicture', function(req, res, next) {
var imgPath = __dirname + "/no_photo.png";
// var imgPath = __dirname + "/photototo.jpg";
fs.access(imgPath, fs.F_OK, (error) => {
if (error) {
console.log(error);
}
else {
res.sendFile(imgPath, (err) => { if (err) next(err); });
}
});
})
And I'm trying to display the picture like this:
var url = "data:image/png;base64,"+this.props.picture;
return (
<div>
<h1>Change your profile pictures</h1>
<img src={url} alt={'hello'}/>
</div>
);
But here is the result:
I don't know what can I do.. I tried to remove newlines and other spaces
with url.replace(/\s+/g, '') but it's not working.
UPDATE: I just replaced with this and it works :
router.post('/loadpicture', function(req, res, next) {
var imgPath = __dirname + "/no_photo.png";
var img = fs.readFileSync(imgPath);
res.writeHead(200, {'Content-Type': 'image/png' });
res.end(img.toString('base64'));
})
Related
i want to send image to a server and getting the result with a json format but the application returns a Network Request failed error
react native 0.6 using genymotion as emulator
i tried RNFetchblob but the result take a long time to get response (5 min )
also i tried axios but it response with empty data with 200 ok
this is the function that import the image
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
and this method that sends the image
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.avatarSource , name:'file.jpeg'});
fetch(url, {
method: 'POST',
body:UplodedFile
})
.then(response => response.json())
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});
i expect json format
ScreenShot here
can you change your code like this?
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
pickerResponse: response,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.pickerResponse.path , name:'file.jpeg'});
axios({
method: "post",
url: url,
data: UplodedFile
})
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});
I Need Access to file name in my request body because i want store in my db but i dont know handle that , this is my code :
var storage = multer.diskStorage({
destination: function (req, file, callback) {
var name = 'public/images/' + Math.floor((Math.random() * 10675712320) + 1);
fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
** Im want pass name variable**
callback(null, name);
}
});
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
var upload = multer({storage: storage}).single('userPhoto');
app.post('/api/photo', function (req, res) {
***upload(req, res, function (data) {
I need access to file name here because i want store in my db***
console.log(data);
res.end("File is uploaded");
});
});
Im try this way but not working :
fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
callback(name, name);
}
});
you can access to path from req.file.path like this :
var upload = multer({storage: storage}).single('userPhoto');
app.post('/api/photo', function (req, res) {
upload(req, res, function (data) {
console.log(req.file.path);
res.end("File is uploaded");
});
});
I have an issue where I am trying to pass my file information in query parameter form to the route that I have set up to upload my AWS file and then return the url. The issue I am running into is that the form is located within the view file accessed with the /create/comment route and prepended to all of my routes is /app. In my XMLHttpRequest I am requesting /app/sign and the file query parameters, but for some reason it keeps prepending this with /app/create or /app/create/app/sign, which is why I have 404 error. Is there a way a specific method to prevent the prepending of /app/create?
Error function at xhr.send();
function sign_request(file, done) {
var xhr = new XMLHttpRequest();
console.log(xhr);
console.log(file);
xhr.open("GET", "app/sign?file_name=" + file.name + "&file_type=" + file.type);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
done(response);
}
};
xhr.send();
};
Error Message:
comment:139 GET http://localhost:3000/app/create/app/sign?file_name=File-name.png&file_type=image/png 404 (Not Found)
Here is my route setup:
var express = require('express');
var router = express.Router();
router.use('/app');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var models = require('../models/db-index');
var fs = require('fs');
var aws = require('aws-sdk');
/*==== /SIGN ====*/
router.get('/sign', function(req, res){
aws.config.update({accessKeyId: config.awsAccessKeyId, secretAccessKey: config.awsSecretAccessKey});
var s3 = new aws.S3()
var options = {
Bucket: config.awsBucket,
Region: 'us-east-1',
Key: req.query.file_name,
Expires: 60,
ContentType: req.query.file_type,
ACL: 'public-read'
}
s3.getSignedUrl('putObject', options, function(err, data){
if(err) return res.send('Error with S3')
res.json({
signed_request: data,
url: 'https://s3.amazonaws.com/' + S3_BUCKET + '/' + req.query.file_name
});
});
});
router.get('/create/comment',function(req, res){
models.DiscoverySource.findAll({
where: {
organizationId: req.user.organizationId
}, attributes: ['discoverySourceName']
}).then(function(discoverySource){
res.render('pages/app/comment-create.hbs',{
discoverySource: discoverySource
});
});
});
Form (Accessed at /app/create/comment):
<!DOCTYPE html>
<head>
{{> app/app-head}}
</head>
<body>
{{> app/app-navigation}}
<div class="container">
<div class="col-md-12">
<div class="row-form-container">
<label for="report-link">File Attachment:</label>
<input type="file" name="fileAttachment" id="image">
<img id="preview">
</div>
</div>
<script type="text/javascript">
function upload(file, signed_request, url, done) {
var xhr = new XMLHttpRequest();
xhr.open("PUT", signed_request);
xhr.setRequestHeader('x-amz-acl', 'public-read');
xhr.onload = function() {
if (xhr.status === 200) {
done();
};
};
xhr.send(file);
}
function sign_request(file, done) {
console.log('work please');
var xhr = new XMLHttpRequest();
console.log(xhr);
console.log(file);
xhr.open("GET", "app/sign?file_name=" + file.name + "&file_type=" + file.type);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
done(response);
}
};
xhr.send();
};
document.getElementById("image").onchange = function() {
var file = document.getElementById("image").files[0]
if (!file) return
sign_request(file, function(response) {
upload(file, response.signed_request, response.url, function() {
document.getElementById("preview").src = response.url
});
});
};
</script>
</body>
Adding a / before app/sign when you send a request will prevent the prepending of current subpath.
Try:
xhr.open("GET", "/app/sign?file_name=" + file.name + "&file_type=" + file.type);
I was wondering how to convert Variable-length binary data(255216255224016747073700110010100255) to a jpeg or png to the web browser?
Example Code:
var Connection = require('tedious').Connection;
var config = {
"userName": "user#server.database.windows.net",
"password": "pswd",
"server": "server.database.windows.net",
"options": {
"database": "db",
"encrypt": true,
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
console.log("Connected");
}
);
var Request = require('tedious').Request;
var result,
resG;
function sendResponse() {
var vals;
// Convert to string then array
var resultA = result.toString().split(',');
// Now I can loop through the data returned
resultA.forEach(function(val, index, ar) {
if(vals == null) {
vals = val;
} else {
vals += val;
}
});
resG.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': vals.length});
//console.log(vals);
//resG.end("<img src=\"data:image/jpg;base64," + vals + "\" />");
// Output data returned from db as string
resG.end("" + vals);
}
function executeStatement() {
request = new Request("SELECT Photos FROM dbo.tbl WHERE FarmerFirstName='someName' AND FarmerLastName='someLastName'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
result = column.value;
});
});
request.on('doneInProc', function(rowCount, more) {
// Got everything needed from db move on to sending a response
sendResponse();
});
connection.execSql(request);
}
var http = require('http'),
director = require('director');
var router = new director.http.Router({
"/": {
get: executeStatement
}
});
var server = http.createServer(function (req, res) {
// set global res var
resG = res;
router.dispatch(req, res, function (err) {
if (err) {
res.writeHead(404);
res.end();
}
});
});
server.listen(80);
I'm using tedious for my db connector and director as my router.
The result is already an array of bytes for the Image. You do not need to do any fancy transformations on it. This should work.
function sendResponse() {
resG.writeHead(200, {'Content-Type': 'image/jpeg', 'Content-Length': result.length});
resG.end(new Buffer(result));
}
or if you want to serve it as part of an HTML page, this:
function sendResponse() {
resG.writeHead(200, {'Content-Type': 'text/html'});
var vals = (new Buffer(result)).toString('base64')
resG.end("<html><body>" +
"<img src=\"data:image/jpg;base64," + vals + "\" />" +
"</body></html>");
}
I want use formidable with express in node.js to achieve upload image function,
what I do is :
app.configure(function () {
app.use(express.static(__dirname + "/media"));
app.use(express.bodyParser());
})
app.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files){
console.log("log in parse");
console.log("fields type is " + typeof fields);
console.log("files type is " + typeof files);
console.log(files.image);
if (err) return res.send('You found error');
});
})
with this code, the image could upload successully, but the form.parse function seems doesn't been invoked, cuz the log doesn't been invoked
Why?What's wrong with my code?
express 3 bodyParser() uses formidable internally.
So this should work:
view.jade
form#fileupload(enctype="multipart/form-data")
input(type="hidden",name="user[id]", value="1")
input(type="file",name="photo[file]")
app.js
app.post('/upload', function (req, res) {
var userId = req.body.user.id;
var photo = req.files.photo.file;
});