【问题标题】:How to access files on digital ocean spaces with multer如何使用 multer 访问数字海洋空间上的文件
【发布时间】:2018-06-24 16:43:49
【问题描述】:

我已经设法使用节点 js 应用程序在数字海洋空间上上传 pdf 文件,如下所示。 我不知道如何访问这些文件并将它们显示给用户。我从本教程中获得了以下代码,object storage file upload,,但没有关于如何访问文件的示例。 当我只是尝试使用他们的 url 访问它们时,我只会得到空白。 我已将它们公开,但尝试从 url 访问它们仍然一无所获。 有没有办法使用 multer 访问文件,我是否必须使用 RESTFul API 发出获取请求?如何访问存储在数字海洋空间中的文件?

这就是我上传文件的方式

const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");
const spaceEndPoint = new aws.Endpoint("ams3.digitaloceanspaces.com");
const s3 = new aws.S3({
	endpoint:spaceEndPoint
})

const upload = multer({
	storage:multerS3({
		s3:s3,
		bucket: "fileRepo",
		acl:"public-read",
		key:function(request, file, cb){
			console.log(file);
			cb(null, file.originalname);
		}
	})
}).array("upload",1);

router.get("uploadFile", function(req,res){
	upload(req, res, function(error){
		if(error){
			console.log(error);
			return res.redirect("/");
		}
	});
})

这就是我尝试检索 pdf 的方式

router.get("/contentPage", function(req, res){

	var fileName = req.body.department;
	var directory = "https://fileRepo.ams3.digitaloceanspaces.com/" + fileName + ".pdf";
	res.render("fileview", {dir: directory});
})

<div id="departmentListWrapper" class="container">
	<embed src="<%= dir %>" width="800px" height="2100px" />
</div>

谁能告诉我检索这些文件可能会出现什么问题?

【问题讨论】:

    标签: node.js amazon-s3 object-storage


    【解决方案1】:

    试试这个代码 sn-p,对我来说很好

    import multer from 'multer';
    import multerS3 from 'multer-s3';
    
    aws.config.update({
      accessKeyId: 'your access key',
      secretAccessKey: 'your secret key'
    });
    var filepath = "path of files folder"
    // Create an S3 client setting the Endpoint to DigitalOcean Spaces
    var spacesEndpoint = new aws.Endpoint('nyc3.digitaloceanspaces.com');
    var s3 = new aws.S3({endpoint: spacesEndpoint});
    
      var params = {
        Bucket: bucketName, 
        Key: keyName, 
        Body: fs.createReadStream(filepath),
        ACL: 'public-read'
      };
    
      s3.putObject(params, async function(err, data) {
        if (err) {
          console.log(err);
        } else {
          console.log(data);
        }
      });
    

    【讨论】:

      【解决方案2】:

      原来数字海洋不知道上传的是什么类型的文件,我必须让它在上传之前读取文件类型,以便浏览器知道我试图上传的文件类型通过添加行

      内容类型:multerS3.AUTO_CONTENT_TYPE

      到 multer 对象,使其看起来像这样。

      const upload = multer({
      	storage:multerS3({
      		s3:s3,
      		bucket: "fileRepo",
              contentType: multerS3.AUTO_CONTENT_TYPE
      		acl:"public-read",
      		key:function(request, file, cb){
      			console.log(file);
      			cb(null, file.originalname);
      		}
      	})
      }).array("upload",1);

      【讨论】:

        猜你喜欢
        • 2021-10-24
        • 2021-12-26
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        • 2019-03-26
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        相关资源
        最近更新 更多