作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
几天来我一直在尝试将简单的个人资料图像保存到我的 MongoDB 数据库,但取得的成功有限。看来是相当的痛苦。我可以让它存储图像,但不能用路径检索它。我读到,最好将图像存储在其他地方(在我的例子中是注册域),并且仅将图像的 url 存储在数据库中。如何使用 MEAN 堆栈实现此目的?这可能吗?
还有什么好的、可能免费的服务可用吗?
示例:
router.post('/upload/:profile_id', function (req, res) {
//post to a folder on my external domain
});
最佳答案
您可以使用 firebase 轻松存储图像或任何二进制文件。
您可以通过以下方式设置存储空间:
// Set the configuration for your app
// TODO: Replace with your project's config object
var config = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket>'
};
firebase.initializeApp(config);
// Get a reference to the storage service, which is used to create references in your storage bucket
var storageRef = firebase.storage().ref();
这是有关如何上传图像的示例:
// File or Blob, assume the file is called rivers.jpg
var file = ...
// Upload the file to the path 'images/rivers.jpg'
// We can use the 'name' property on the File API to get our file name
var uploadTask = storageRef.child('images/' + file.name).put(file);
// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// See below for more detail
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
var downloadURL = uploadTask.snapshot.downloadURL;
});
最后..下载图像:
// Create a reference to the file we want to download
var imageRef = storageRef.child('images/example.jpg');
// Get the download URL
imageRef.getDownloadURL().then(function(url) {
// Insert url into an <img> tag to "download"
}).catch(function(error) {
switch (error.code) {
case 'storage/object_not_found':
// File doesn't exist
break;
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
...
case 'storage/unknown':
// Unknown error occurred, inspect the server response
break;
}
});
关于javascript - 如何使用 MEAN 堆栈将上传的图像存储到我的其他域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38226045/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!