我将 pdf 文件上传到 S3 时遇到问题。 上传过程成功,我可以在存储桶中看到我的文件。 但每当我尝试下载或查看存储桶中的文件时,我都会收到此错误“错误 无法加载 PDF 文档。”尝试从不同的浏览器打开文件,但出现相同的错误。这是我处理此问题的代码 使用“https://gist.github.com/binhp/52e2254420a638d9da5c4cf33dde3c46”的库
/**
函数 onRequest(scriptContext) {
var awsAccessKey = "";
var awsSecretKey = "";
var awsBucketName = "";
var awsContentEncoding = "UTF-8";
var selectedFile = nfile.load({ id: 11987 });
var fileNameSplit = selectedFile.name.split(".");
var fileExtension = fileNameSplit.pop();
var fileName = fileNameSplit.shift();
var selectedFileContent = selectedFile.getContents();
var keyFileName = fileName + "-" + Date.now() + "." + fileExtension;
var option = {
region: "ap-southeast-1",
accessKeyId: awsAccessKey,
secretAccessKey: awsSecretKey,
};
var s3Obj = new AWS.S3(option);
const params ={
Bucket: awsBucketName,
Key: keyFileName,
Body: selectedFileContent,
// ContentEncoding: awsContentEncoding,
ServerSideEncryption: 'AES256', // Optional
ACL: "public-read-write" ,
ContentType: getContentTypeByFileExtension(fileExtension),
};
s3Obj.putObject( params , function (err,data) {
if (err) {
nLog.error("s3Error", JSON.stringify(err));
} else {
nLog.debug("S3putObject", JSON.stringify(data));
}
}
);
var preSignedUrlParams = {
Bucket: awsBucketName,
Key: keyFileName,
};
var preSignedUrl = s3Obj.getSignedUrl("getObject", preSignedUrlParams);
nLog.debug("Pre-signed URL:", preSignedUrl);
// Retrieve file content from the pre-signed URL
var response = https.get({ url: preSignedUrl });
if (response.code === 200) {
var fileContent = response.body;
// Process the file content here
} else {
nLog.debug("Error retrieving file content. HTTP response code:", response.code);
}
var file = nfile.create({
name: "file_name.pdf",
fileType: nfile.Type.PDF,
contents: fileContent,
folder: -20, // Replace with the appropriate folder ID
});
var fileId = file.save();
nLog.debug("file save with id" + fileId)
}
函数 getContentTypeByFileExtension(fileExtension) { var 内容类型;
switch (fileExtension.toLowerCase()) {
case "pdf":
contentType = "application/pdf";
break;
case "png":
contentType = "image/png";
break;
case "jpg":
case "jpeg":
contentType = "image/jpeg";
break;
case "txt":
contentType = "text/plain";
break;
// Add more cases for other file extensions as needed
default:
contentType = "application/octet-stream"; // Fallback content type
break;
}
return contentType;
}
返回{ onRequest: onRequest, }; });
但是,当我尝试从 s3 存储桶获取上传的文件时,它会正确检索内容。
我尝试使用 Upload() 函数而不是 putObject() 但总是收到此错误“错误:代码 400:”没有消息正文
您可以使用“渲染”模块读取文件内容并尝试上传那些应该可以工作的文件内容。
let renderer = render.create();
renderer.addCustomDataSource({
format: render.DataSource.OBJECT,
alias: "pdf data",
data: pdfData,
});
var newfile = renderer.renderAsPdf();
let fileContents = newfile.getContents();
并上传文件内容。