【问题标题】:how to find the path of an image I want to upload?如何找到我要上传的图像的路径?
【发布时间】:2020-05-20 03:33:14
【问题描述】:

我正在尝试学习 AWS S3,因此我正在构建一个用于上传和稍后下载我上传的图像的表单。

如果我上传位于应用程序同一目录中的图像,目前一切正常。它将出现在我的 S3 存储桶中。但是如果我尝试从另一个目录上传图片,我会收到这个错误:

Error: ENOENT: no such file or directory, open 'myphoto.jpg'
at Object.openSync (fs.js:443:3)
at Object.readFileSync (fs.js:343:35)
at uploadFile (/home/morbi/bucketTest/upload.js:14:26)
at /home/morbi/bucketTest/app.js:65:3
at Layer.handle [as handle_request] (/home/morbi/bucketTest/node_modules/express/lib/router/layer.js:95:5)
at next (/home/morbi/bucketTest/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/morbi/bucketTest/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/morbi/bucketTest/node_modules/express/lib/router/layer.js:95:5)
at /home/morbi/bucketTest/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/morbi/bucketTest/node_modules/express/lib/router/index.js:335:12)

这是我的表格,这是一个非常简单的表格,用于测试目的,index.ejs:

<html>
  <head>
    <title>Bucket Test</title>
  </head>
  <body>
    <a href="/bucket">Create Bucket</a>

    <form action="/" method="POST">
      <label for="img">Select image:</label>
      <input type="file" id="img" name="img" accept="image/*">
      <input type="submit">
    </form>
  </body>
</html>

这是我的 app.js:

// load .env data into process.env
require('dotenv').config();

// Web server config
const PORT       = process.env.PORT || 8080;
const ENV        = process.env.ENV || "development";
const AWS = require('aws-sdk');

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const uploadFile = require("./upload.js");


// Enter copied or downloaded acess ID and secret key here
const ID = process.env.BUCKET_ID;
const SECRET = process.env.BUCKET_SECRET;

// The name of the bucket that you have created
const BUCKET_NAME = process.env.BUCKET_NAME;
const BUCKET_AREA = process.env.BUCKET_AREA;

const s3 = new AWS.S3({
  accessKeyId: ID,
  secretAccessKey: SECRET
});

const params = {
  Bucket: BUCKET_NAME
};

app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));

app.get("/", function(req,res){
  res.render("index");
});

app.get("/bucket", function(req,res){

  let string;

  s3.createBucket(params, function(err, data){
    if (err) {
      console.log(err, err.stack);
    } else {
      string = data.location;
      console.log('Bucket Created Successfully', data.location);
    }
  });

  res.render("bucket", {string: string});
});

app.get("/upload", function(req, res){
  console.log(req.body);
  // let img = req.body;
  res.render("download");
});

app.post("/", function(req,res){
  let item = req.body.img;
  console.log(item);
  uploadFile(item);
  res.redirect("upload", /* {item: item} */);
});

app.listen(PORT, process.env.IP, function(){
  console.log(`Example app listening on port ${PORT}`);
});

这是我的upload.js:

const fs = require('fs');
const AWS = require('aws-sdk');
const BUCKET_NAME = process.env.BUCKET_NAME;
const ID = process.env.BUCKET_ID;
const SECRET = process.env.BUCKET_SECRET;

const s3 = new AWS.S3({
  accessKeyId: ID,
  secretAccessKey: SECRET
});

const uploadFile = (fileName) => {
  // Read content from the file
  const fileContent = fs.readFileSync(fileName);

  // Setting up S3 upload parameters
  const params = {
    Bucket: BUCKET_NAME,
    Key: fileName, // File name you want to save as in S3
    Body: fileContent
  };

  // Uploading files to the bucket
  s3.upload(params, function(err, data) {
    if (err) {
      throw err;
    } else {
      console.log(`File uploaded successfully. ${data.location}`);
    }
  });
};

module.exports = uploadFile;

我假设它不起作用的原因是因为当我选择文件/图像时,它只传递文件名而不是路径。那么如何附加文件的路径呢?

【问题讨论】:

    标签: javascript html node.js amazon-s3 ejs


    【解决方案1】:

    我想通了,在 youtube 上看到了一些他们使用 Multer 和 Multer-s3 的视频,但我不想改变我的 upload.js 文件,所以我遇到了 express-upload 包,创建了一个文件夹在我的应用程序目录中传输图像,然后将它们发送到我的存储桶,一切正常。

    这是我更新的文件:

    app.js:

    // load .env data into process.env
    require('dotenv').config();
    
    // Web server config
    const PORT       = process.env.PORT || 8080;
    const ENV        = process.env.ENV || "development";
    const AWS = require('aws-sdk');
    
    const express = require("express");
    const app = express();
    const bodyParser = require("body-parser");
    const uploadFile = require("./upload.js");
    
    const fileUps = require('express-fileupload');
    
    
    // Enter copied or downloaded acess ID and secret key here
    const ID = process.env.BUCKET_ID;
    const SECRET = process.env.BUCKET_SECRET;
    
    // The name of the bucket that you have created
    const BUCKET_NAME = process.env.BUCKET_NAME;
    const BUCKET_AREA = process.env.BUCKET_AREA;
    
    const s3 = new AWS.S3({
      accessKeyId: ID,
      secretAccessKey: SECRET
    });
    
    const params = {
      Bucket: BUCKET_NAME
    };
    
    app.use(bodyParser.urlencoded({extended: true}));
    app.set("view engine", "ejs");
    app.use(express.static(__dirname + "/public"));
    app.use(fileUps());
    
    app.get("/", function(req,res){
      res.render("index");
    });
    
    app.get("/bucket", function(req,res){
    
      let string;
    
      s3.createBucket(params, function(err, data){
        if (err) {
          console.log(err, err.stack);
        } else {
          string = data.location;
          console.log('Bucket Created Successfully', data.location);
        }
      });
    
      res.render("bucket", {string: string});
    });
    
    app.get("/upload", function(req, res){
      console.log(req.body);
      // let img = req.body;
      res.render("download");
    });
    
    app.post("/", function(req,res){
      if(req.files === null) {
        return res.status(400).json({ msg: 'No file uploaded' });
      }
      const file = req.files.img;
    
      file.mv(`${__dirname}/uploads/${file.name}`, function(err) {
        if(err) {
          console.error(err);
          return res.status(500).send(err);
        }
    
    
      });
    
      console.log(file);
    
      uploadFile(file.data ,file.name);
      res.redirect("upload", {item: file.name});
    });
    
    app.listen(PORT, process.env.IP, function(){
      console.log(`Example app listening on port ${PORT}`);
    });
    

    和upload.js:

    const AWS = require('aws-sdk');
    const BUCKET_NAME = process.env.BUCKET_NAME;
    const ID = process.env.BUCKET_ID;
    const SECRET = process.env.BUCKET_SECRET;
    
    const s3 = new AWS.S3({
      accessKeyId: ID,
      secretAccessKey: SECRET
    });
    
    const uploadFile = (fileData, fileName) => {
      // Read content from the file
      const fileContent = fileData;
    
      // Setting up S3 upload parameters
      const params = {
        Bucket: BUCKET_NAME,
        Key: fileName, // File name you want to save as in S3
        Body: fileContent
      };
    
      // Uploading files to the bucket
      s3.upload(params, function(err, data) {
        if (err) {
          throw err;
        } else {
          console.log(`File uploaded successfully. ${data.location}`);
        }
      });
    };
    
    module.exports = uploadFile;
    

    现在我需要做的就是在上传文件夹中的文件被发送到 s3 存储桶后删除它,这样服务器就不会用完空间。

    希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 2023-03-09
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多