김현기

화면에 출력 기능까지 구현

1 node_modules/ 1 node_modules/
2 -package-lock.json
3 package.json 2 package.json
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -5,8 +5,8 @@ var path = require('path'); ...@@ -5,8 +5,8 @@ var path = require('path');
5 var cookieParser = require('cookie-parser'); 5 var cookieParser = require('cookie-parser');
6 var logger = require('morgan'); 6 var logger = require('morgan');
7 var fs = require('fs') 7 var fs = require('fs')
8 -var AWS = require('aws-sdk'); 8 +var AWS = require('aws-sdk'); // AWS 의 서비스를 이용하기 위해 사용
9 - 9 +const { Rekognition } = require('aws-sdk');
10 10
11 // 이미지를 저장할 버킷 이름 11 // 이미지를 저장할 버킷 이름
12 var bucketName = "kindofyourdogimage"; 12 var bucketName = "kindofyourdogimage";
...@@ -15,98 +15,14 @@ var bucketRegion = 'ap-northeast-2'; ...@@ -15,98 +15,14 @@ var bucketRegion = 'ap-northeast-2';
15 // access key 15 // access key
16 var accessId= 'your_accessId'; 16 var accessId= 'your_accessId';
17 // access secret key 17 // access secret key
18 -var secretKey = 'your_secretKey'; 18 +var secretKey = 'yout_secretKey';
19 // AWS Cognito 인증 19 // AWS Cognito 인증
20 -//var identityPoolId = "ap-northeast-2:7cba9a17-588b-40d6-8c70-eb8ba4d573be";
21 -
22 -
23 -// AWS의 config 정보를 Update해준다 -> 이용자가 S3 버킷에 접근 가능하다
24 -/*
25 -AWS.config.update({
26 - region:bucketRegion,
27 - credentials:new AWS.CognitoIdentityCredentials({
28 - IdentityPoolId:identityPoolId,
29 - })
30 -})
31 -*/
32 AWS.config.update({ 20 AWS.config.update({
33 region:bucketRegion, 21 region:bucketRegion,
34 accessKeyId:accessId, 22 accessKeyId:accessId,
35 secretAccessKey:secretKey 23 secretAccessKey:secretKey
36 }); 24 });
37 25
38 -// 내가 사용할 S3
39 -var s3 = new AWS.S3({
40 - apiVersion: "2006-03-01",
41 - params: {Bucket: bucketName}
42 -});
43 -
44 -const fileName = 'puppy.jpg';
45 -
46 -// 파일 업로드
47 -const uploadFile = (fileName) => {
48 - const fileContent = fs.readFileSync(fileName);
49 - const params = {
50 - Bucket: bucketName,
51 - Key: fileName, // File name you want to save as in S3
52 - Body: fileContent }
53 -;
54 - s3.upload(params, function(err, data) {
55 - if (err) { throw err; }
56 - console.log(`File uploaded successfully. ${data.Location}`);
57 - });
58 -};
59 -uploadFile(fileName);
60 -
61 -/*
62 -// rekognition 객체
63 -const client = new AWS.Rekognition();
64 -
65 -const params = {
66 - "Image": {
67 - "S3Object": {
68 - "Bucket": bucketName,
69 - "Name": fileName
70 - }
71 - },
72 - "MaxLabels": 10,
73 - "MinConfidence": 75
74 -}
75 -
76 -
77 -
78 -// 이미지 분석하기
79 -client.detectLabels(params, function(err, response) {
80 - if (err) {
81 - console.log(err, err.stack); // an error occurred
82 - } else {
83 - console.log(`Detected labels for: ${photo}`)
84 - response.Labels.forEach(label => {
85 - console.log(`Label: ${label.Name}`)
86 - console.log(`Confidence: ${label.Confidence}`)
87 - console.log("Instances:")
88 - label.Instances.forEach(instance => {
89 - let box = instance.BoundingBox
90 - console.log(" Bounding box:")
91 - console.log(` Top: ${box.Top}`)
92 - console.log(` Left: ${box.Left}`)
93 - console.log(` Width: ${box.Width}`)
94 - console.log(` Height: ${box.Height}`)
95 - console.log(` Confidence: ${instance.Confidence}`)
96 - })
97 - console.log("Parents:")
98 - label.Parents.forEach(parent => {
99 - console.log(` ${parent.Name}`)
100 - })
101 - console.log("------------")
102 - console.log("")
103 - }) // for response.labels
104 - } // if
105 -});
106 -*/
107 -
108 -var indexRouter = require('./routes/index');
109 -var usersRouter = require('./routes/users');
110 // image업로드 시 해당 route기능 사용 26 // image업로드 시 해당 route기능 사용
111 27
112 var app = express(); 28 var app = express();
...@@ -121,90 +37,75 @@ app.use(express.urlencoded({ extended: false })); ...@@ -121,90 +37,75 @@ app.use(express.urlencoded({ extended: false }));
121 app.use(cookieParser()); 37 app.use(cookieParser());
122 app.use(express.static(path.join(__dirname, 'public'))); 38 app.use(express.static(path.join(__dirname, 'public')));
123 39
124 -app.use('/', indexRouter);
125 -app.use('/users', usersRouter);
126 40
127 // image 올리는 화면 41 // image 올리는 화면
128 -app.get('/form', function(req, res){ 42 +app.get('/', function(req, res){
129 - var output = ` 43 + res.render('index');
130 - <html>
131 - <body>
132 - <form enctype="multipart/form-data" method="post" action="upload_receiver">
133 - <input type="file" name="userfile">
134 - <input type="submit">
135 - </form>
136 - </body>
137 - </html>
138 - `;
139 - res.send(output);
140 - console.log(output);
141 }); 44 });
142 45
143 // image를 받았을 때 46 // image를 받았을 때
144 app.post('/upload_receiver', function(req,res){ 47 app.post('/upload_receiver', function(req,res){
48 + //rekognition 객체
49 +
50 + var dogKind = "";
51 + //req 받아옴
145 var form = new formidable.IncomingForm(); 52 var form = new formidable.IncomingForm();
146 - console.log(form);
147 - const client = new AWS.Rekognition();
148 -
149 - const params = {
150 - "Image": {
151 - "S3Object": {
152 - "Bucket": bucketName,
153 - "Name": fileName
154 - }
155 - },
156 - "MaxLabels": 10,
157 - "MinConfidence": 75
158 - }
159 -
160 - // 이미지 분석하기
161 - client.detectLabels(params, function(err, response) {
162 - if (err) {
163 - console.log(err, err.stack); // an error occurred
164 - } else {
165 - console.log(`Detected labels for: ${form.name}`)
166 - response.Labels.forEach(label => {
167 - console.log(`Label: ${label.Name}`)
168 - console.log(`Confidence: ${label.Confidence}`)
169 - console.log("Instances:")
170 - label.Instances.forEach(instance => {
171 - let box = instance.BoundingBox
172 - console.log(" Bounding box:")
173 - console.log(` Top: ${box.Top}`)
174 - console.log(` Left: ${box.Left}`)
175 - console.log(` Width: ${box.Width}`)
176 - console.log(` Height: ${box.Height}`)
177 - console.log(` Confidence: ${instance.Confidence}`)
178 - })
179 - console.log("Parents:")
180 - label.Parents.forEach(parent => {
181 - console.log(` ${parent.Name}`)
182 - })
183 - console.log("------------")
184 - console.log("")
185 - }) // for response.labels
186 - } // if
187 - });
188 53
189 - // S3에 upload해주기 54 + //form을 종류별로 파싱함
190 form.parse(req, function(err, fields, files){ 55 form.parse(req, function(err, fields, files){
56 + //s3객체를 만듦
191 var s3 = new AWS.S3(); 57 var s3 = new AWS.S3();
58 + //s3에 저장할 형식을 만듦
192 var params = { 59 var params = {
193 Bucket:bucketName, 60 Bucket:bucketName,
194 ACL:'public-read', 61 ACL:'public-read',
195 Key:files.userfile.name, 62 Key:files.userfile.name,
196 Body: require('fs').createReadStream(files.userfile.path) 63 Body: require('fs').createReadStream(files.userfile.path)
197 } 64 }
65 + console.log(files.userfile.name);
66 + //s3에 저장함
198 s3.upload(params, function(err, data){ 67 s3.upload(params, function(err, data){
199 var result=''; 68 var result='';
200 if(err) 69 if(err)
201 result = 'Fail'; 70 result = 'Fail';
202 - else 71 + else{
72 + params = {
73 + "Image": {
74 + "S3Object": {
75 + "Bucket": bucketName,
76 + "Name": files.userfile.name
77 + }
78 + },
79 + "MaxLabels": 10,
80 + "MinConfidence": 75
81 + };
82 +
83 +
84 + // rekogition으로 데이터 분석
85 +
86 + var client = new Rekognition();
87 +
88 + client.detectLabels(params, function(err, response) {
89 + console.log(params);
90 + response.Labels.some(label => {
91 + if(label.Parents.length > 4 && label.Name != 'Puppy') {
92 + console.log(label.Name);
93 + dogKind = label.Name;
94 + console.log(dogKind);
95 + res.render('kind',{dogKind:dogKind});
96 + return true;
97 + }
98 + });
99 +
100 + });
203 result = `<img src="${data.Location}>`; 101 result = `<img src="${data.Location}>`;
204 - res.send(`<html><body>${result}</body></html`) 102 + console.log(result);
103 + }
205 }); 104 });
206 - console.log(err, fields,files); 105 +
207 }); 106 });
107 +
108 + //console.log(err, fields,files)
208 }); 109 });
209 110
210 // catch 404 and forward to error handler 111 // catch 404 and forward to error handler
......
This diff is collapsed. Click to expand it.
1 body { 1 body {
2 + background-color: burlywood;
2 padding: 50px; 3 padding: 50px;
3 font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; 4 font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
4 } 5 }
......
1 -var express = require('express');
2 -var router = express.Router();
3 -
4 -/* GET home page. */
5 -router.get('/', function(req, res, next) {
6 - res.render('index', { title: 'KindOfYourDog' });
7 -});
8 -
9 -module.exports = router;
1 -var express = require('express');
2 -var router = express.Router();
3 -
4 -/* GET users listing. */
5 -router.get('/', function(req, res, next) {
6 - res.send('respond with a resource');
7 -});
8 -
9 -module.exports = router;
...\ No newline at end of file ...\ No newline at end of file
1 <!DOCTYPE html> 1 <!DOCTYPE html>
2 <html> 2 <html>
3 <head> 3 <head>
4 - <!-- **DO THIS**: --> 4 + <title>KindOfYourDog</title>
5 - <!-- Replace SDK_VERSION_NUMBER with the current SDK version number --> 5 + <meta charset="utf-8" />
6 - <script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.js"></script> 6 + <link rel="stylesheet" href="stylesheets/style.css">
7 - <script src="./app.js"></script>
8 - <script>
9 - function getHtml(template) {
10 - return template.join('\n');
11 - }
12 - listAlbums();
13 - </script>
14 </head> 7 </head>
15 <body> 8 <body>
16 - <h1>My Photo Albums App</h1> 9 + <h1>Kind of Your Dog</h1>
17 - <div id="app"></div> 10 + <div>
11 + <img src = "puppy.jpg">
12 +
13 + </div>
14 + <div>
15 + <form enctype="multipart/form-data" method="post" action="upload_receiver">
16 + <input type="file" accept="image/*" name="userfile">
17 + <input type="submit">
18 + </form>
19 + </div>
20 + <div>
21 + <h2>이 개의 종류는</h2>
22 + </div>
18 </body> 23 </body>
19 -</html>
...\ No newline at end of file ...\ No newline at end of file
24 +</html>
......
1 +<!DOCTYPE html>
2 +<html>
3 + <head>
4 + <title>KindOfYourDog</title>
5 + <meta charset="utf-8" />
6 + <link rel="stylesheet" href="stylesheets/style.css">
7 + </head>
8 + <body>
9 + <h1>Kind of Your Dog</h1>
10 + <div>
11 + <form enctype="multipart/form-data" method="post" action="upload_receiver">
12 + <input type="file" accept="image/*" name="userfile" id="userfile" >
13 + <input type="submit">
14 + </form>
15 + </div>
16 + <div>
17 + <h2>이 개의 종류는</h2>
18 + <h3><%=dogKind%></h3>
19 + </div>
20 + </body>
21 +</html>