김현기

화면에 출력 기능까지 구현

node_modules/
package-lock.json
package.json
\ No newline at end of file
......
......@@ -5,8 +5,8 @@ var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var fs = require('fs')
var AWS = require('aws-sdk');
var AWS = require('aws-sdk'); // AWS 의 서비스를 이용하기 위해 사용
const { Rekognition } = require('aws-sdk');
// 이미지를 저장할 버킷 이름
var bucketName = "kindofyourdogimage";
......@@ -15,98 +15,14 @@ var bucketRegion = 'ap-northeast-2';
// access key
var accessId= 'your_accessId';
// access secret key
var secretKey = 'your_secretKey';
var secretKey = 'yout_secretKey';
// AWS Cognito 인증
//var identityPoolId = "ap-northeast-2:7cba9a17-588b-40d6-8c70-eb8ba4d573be";
// AWS의 config 정보를 Update해준다 -> 이용자가 S3 버킷에 접근 가능하다
/*
AWS.config.update({
region:bucketRegion,
credentials:new AWS.CognitoIdentityCredentials({
IdentityPoolId:identityPoolId,
})
})
*/
AWS.config.update({
region:bucketRegion,
accessKeyId:accessId,
secretAccessKey:secretKey
});
// 내가 사용할 S3
var s3 = new AWS.S3({
apiVersion: "2006-03-01",
params: {Bucket: bucketName}
});
const fileName = 'puppy.jpg';
// 파일 업로드
const uploadFile = (fileName) => {
const fileContent = fs.readFileSync(fileName);
const params = {
Bucket: bucketName,
Key: fileName, // File name you want to save as in S3
Body: fileContent }
;
s3.upload(params, function(err, data) {
if (err) { throw err; }
console.log(`File uploaded successfully. ${data.Location}`);
});
};
uploadFile(fileName);
/*
// rekognition 객체
const client = new AWS.Rekognition();
const params = {
"Image": {
"S3Object": {
"Bucket": bucketName,
"Name": fileName
}
},
"MaxLabels": 10,
"MinConfidence": 75
}
// 이미지 분석하기
client.detectLabels(params, function(err, response) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log(`Detected labels for: ${photo}`)
response.Labels.forEach(label => {
console.log(`Label: ${label.Name}`)
console.log(`Confidence: ${label.Confidence}`)
console.log("Instances:")
label.Instances.forEach(instance => {
let box = instance.BoundingBox
console.log(" Bounding box:")
console.log(` Top: ${box.Top}`)
console.log(` Left: ${box.Left}`)
console.log(` Width: ${box.Width}`)
console.log(` Height: ${box.Height}`)
console.log(` Confidence: ${instance.Confidence}`)
})
console.log("Parents:")
label.Parents.forEach(parent => {
console.log(` ${parent.Name}`)
})
console.log("------------")
console.log("")
}) // for response.labels
} // if
});
*/
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// image업로드 시 해당 route기능 사용
var app = express();
......@@ -121,90 +37,75 @@ app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// image 올리는 화면
app.get('/form', function(req, res){
var output = `
<html>
<body>
<form enctype="multipart/form-data" method="post" action="upload_receiver">
<input type="file" name="userfile">
<input type="submit">
</form>
</body>
</html>
`;
res.send(output);
console.log(output);
app.get('/', function(req, res){
res.render('index');
});
// image를 받았을 때
app.post('/upload_receiver', function(req,res){
//rekognition 객체
var dogKind = "";
//req 받아옴
var form = new formidable.IncomingForm();
console.log(form);
const client = new AWS.Rekognition();
const params = {
"Image": {
"S3Object": {
"Bucket": bucketName,
"Name": fileName
}
},
"MaxLabels": 10,
"MinConfidence": 75
}
// 이미지 분석하기
client.detectLabels(params, function(err, response) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log(`Detected labels for: ${form.name}`)
response.Labels.forEach(label => {
console.log(`Label: ${label.Name}`)
console.log(`Confidence: ${label.Confidence}`)
console.log("Instances:")
label.Instances.forEach(instance => {
let box = instance.BoundingBox
console.log(" Bounding box:")
console.log(` Top: ${box.Top}`)
console.log(` Left: ${box.Left}`)
console.log(` Width: ${box.Width}`)
console.log(` Height: ${box.Height}`)
console.log(` Confidence: ${instance.Confidence}`)
})
console.log("Parents:")
label.Parents.forEach(parent => {
console.log(` ${parent.Name}`)
})
console.log("------------")
console.log("")
}) // for response.labels
} // if
});
// S3에 upload해주기
//form을 종류별로 파싱함
form.parse(req, function(err, fields, files){
//s3객체를 만듦
var s3 = new AWS.S3();
//s3에 저장할 형식을 만듦
var params = {
Bucket:bucketName,
ACL:'public-read',
Key:files.userfile.name,
Body: require('fs').createReadStream(files.userfile.path)
}
console.log(files.userfile.name);
//s3에 저장함
s3.upload(params, function(err, data){
var result='';
if(err)
result = 'Fail';
else
else{
params = {
"Image": {
"S3Object": {
"Bucket": bucketName,
"Name": files.userfile.name
}
},
"MaxLabels": 10,
"MinConfidence": 75
};
// rekogition으로 데이터 분석
var client = new Rekognition();
client.detectLabels(params, function(err, response) {
console.log(params);
response.Labels.some(label => {
if(label.Parents.length > 4 && label.Name != 'Puppy') {
console.log(label.Name);
dogKind = label.Name;
console.log(dogKind);
res.render('kind',{dogKind:dogKind});
return true;
}
});
});
result = `<img src="${data.Location}>`;
res.send(`<html><body>${result}</body></html`)
console.log(result);
}
});
console.log(err, fields,files);
});
//console.log(err, fields,files)
});
// catch 404 and forward to error handler
......
This diff is collapsed. Click to expand it.
body {
background-color: burlywood;
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
......
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'KindOfYourDog' });
});
module.exports = router;
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<!-- **DO THIS**: -->
<!-- Replace SDK_VERSION_NUMBER with the current SDK version number -->
<script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.js"></script>
<script src="./app.js"></script>
<script>
function getHtml(template) {
return template.join('\n');
}
listAlbums();
</script>
<title>KindOfYourDog</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body>
<h1>My Photo Albums App</h1>
<div id="app"></div>
<h1>Kind of Your Dog</h1>
<div>
<img src = "puppy.jpg">
</div>
<div>
<form enctype="multipart/form-data" method="post" action="upload_receiver">
<input type="file" accept="image/*" name="userfile">
<input type="submit">
</form>
</div>
<div>
<h2>이 개의 종류는</h2>
</div>
</body>
</html>
\ No newline at end of file
</html>
......
<!DOCTYPE html>
<html>
<head>
<title>KindOfYourDog</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body>
<h1>Kind of Your Dog</h1>
<div>
<form enctype="multipart/form-data" method="post" action="upload_receiver">
<input type="file" accept="image/*" name="userfile" id="userfile" >
<input type="submit">
</form>
</div>
<div>
<h2>이 개의 종류는</h2>
<h3><%=dogKind%></h3>
</div>
</body>
</html>