Javascript 在MongoDB后端将图像与Multer一起保存为文件,但不例外
我面临着一个我认为不起作用的问题。 我确实在angularJavascript 在MongoDB后端将图像与Multer一起保存为文件,但不例外,javascript,angular,mongodb,typescript,blob,Javascript,Angular,Mongodb,Typescript,Blob,我面临着一个我认为不起作用的问题。 我确实在angularcrapper.js中安装了一个库https://github.com/matheusdavidson/angular-cropperjs 在前端,我正在处理开发人员开发这个库的一些代码 所以我的迭代将是这样的 裁剪后的图像将被发送到后端的我的api,在那里保存文件并在其他地方显示文件 它保存了一个与blob的链接,这是我的img。 post请求有效,我可以看到img在文件夹中,但当我尝试获取图像时,get有效,但在前端控制台中,它告诉我
crapper.js中安装了一个库https://github.com/matheusdavidson/angular-cropperjs
在前端,我正在处理开发人员开发这个库的一些代码
所以我的迭代将是这样的
裁剪后的图像将被发送到后端的我的api,在那里保存文件并在其他地方显示文件
它保存了一个与blob的链接,这是我的img。
post请求有效,我可以看到img在文件夹中,但当我尝试获取图像时,get有效,但在前端控制台中,它告诉我。
GEThttp://localhost:4200/images/image-160770830007.jpg 404(未找到)
但是在GET
请求中,图像就在那里
{"_id":"5fd3bf6f946e9c40163d82f3",
"imageTitle":"undefined",
"imageDesc":"undefined",
"imageUrl":"/images/image-1607712623266.jpg",
"uploaded":"2020-12-11T18:50:23.288Z","__v":0}
但是,如果我试图与邮递员得到这是不起作用的。
我正试着用这样的邮递员。
http://localhost:4200/images/image-1607713934301.jpg
这与控制台中的错误表相同
`<pre>Cannot GET /images/image-1607713934301.jpg</pre>`
这是我的前端代码。
这是html
imgUrl = "";
image: Image;
imageURL;
imgConfig = {
aspectRatio : 3/4,
dragMode : "move",
background : true,
movable: true,
rotatable : true,
scalable: true,
zoomable: true,
viewMode: 1,
checkImageOrigin : true,
checkCrossOrigin: true
};
fileChangeEvent(event: any): void {
this.imgUrl = URL.createObjectURL(event.target.files[0]);
this.image = event.target.files[0];
}
saveImage() {
console.log(this.image);
const file = new File([this.imgUrl], this.image.type);
this.imageService.addImage(this.image, file).subscribe((res: any) => {
if (res.body) {
this.imageService.getImageByID(res.body._id).subscribe((t: Image) => {
this.imageURL = t.imageUrl;
});
}
}, (err: any) => {
console.log(err);
});
}
这就是服务
const multer = require('multer');
const Image = require("../models/image");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
console.log(cb);
cb(null, path.join(__dirname, '../../../../images'));
},
filename: (req, file, cb) => {
var filetype = '';
if(file.mimetype === 'image/gif') {
filetype = 'gif';
}
if(file.mimetype === 'image/png') {
filetype = 'png';
}
if(file.mimetype === 'image/jpeg') {
filetype = 'jpg';
}
cb(null, 'image-' + Date.now() + '.' + filetype);
}
});
const upload = multer({storage: storage});
routes.get('/:id', function(req, res, next) {
Image.findById(req.params.id, function (err, gallery) {
if (err) return next(err);
res.json(gallery);
});
});
// post data
routes.post('/', upload.single('file'), function(req, res, next) {
if(!req.file) {
return res.status(500).send({ message: 'Upload fail'});
} else {
req.body.imageUrl = req.file.filename;
Image.create(req.body, function (err, image) {
if (err) {
console.log(err);
return next(err);
}
res.json(image);
});
}
});
您的服务器应该发送图像内容。当前,您只使用包含图像路径的JSON进行响应,而不是图像本身。为此,您需要添加文件中间件:
app.use('/images',express.static(path.join(process.cwd(),'../images'))
然后,您应该让您的主机生成正确的URL,您需要更新从服务器返回的对象,如下所示:
routes.get('/:id',函数(req,res,next){
Image.findById(req.params.id,函数(err,gallery){
if(err)返回next(err);
res.json({
…gallery.toJSON(),
imageUrl:`/${req.host}:${req.port}/${gallery.imageUrl}`,
});
});
});
因此,您将为您提供静态内容,并在前端接收正确的URL。在获取裁剪图像时,您可能正在使用
URL.createObjectURL()
。相反,您需要将blob格式的图像上载到服务器。您可以使用toDataUrl()
函数获取blob。@AliWahab这怎么可能?你用什么来裁剪你的图像?我正在使用该库查看github的链接。你能验证你的API是否在postman上工作吗?@PaulRumnik如何发送内容?我在HTML中也有同样的错误。http://localhost:4200/images/image-1607871519730.png 404(未找到)
@Abedin.Zhuniqi express.static将为您解决此问题。您只需确保a)图像正在进入图像文件夹(使用文件管理器)b)图像请求(例如,/images/picture.png
)通过良好(使用浏览器)。我需要将文件夹添加到后端文件夹还是可以在外部执行?我试过了,但它告诉我同样的错误。我不明白你说的“文件管理器”是什么意思?我的意思是你应该上传一个带有你创建的代码的文件,然后确保上传工作正常,并且文件正在服务器上的目标文件夹中。确保您可以打开文件管理器并检查images/Users/abedinzhuniqi/Projects/xxxx/images/
文件夹中是否有新文件。如果是这样,那么express.static应该可以解决这个问题。如果没有文件,那么问题出在代码的其他部分。
imgUrl = "";
image: Image;
imageURL;
imgConfig = {
aspectRatio : 3/4,
dragMode : "move",
background : true,
movable: true,
rotatable : true,
scalable: true,
zoomable: true,
viewMode: 1,
checkImageOrigin : true,
checkCrossOrigin: true
};
fileChangeEvent(event: any): void {
this.imgUrl = URL.createObjectURL(event.target.files[0]);
this.image = event.target.files[0];
}
saveImage() {
console.log(this.image);
const file = new File([this.imgUrl], this.image.type);
this.imageService.addImage(this.image, file).subscribe((res: any) => {
if (res.body) {
this.imageService.getImageByID(res.body._id).subscribe((t: Image) => {
this.imageURL = t.imageUrl;
});
}
}, (err: any) => {
console.log(err);
});
}
export class ImageService {
apiUrl = environment.backend;
constructor(private http: HttpClient) { }
addImage(image: Image, file: File): Observable<any> {
const formData = new FormData();
formData.append("file", file);
formData.append("imageTitle", image.imageTitle);
formData.append("imageDesc", image.imageDesc);
const header = new HttpHeaders();
const params = new HttpParams();
const options = {
params,
reportProgress: true,
headers: header
};
const req = new HttpRequest("POST", this.apiUrl, formData, options);
return this.http.request(req);
}
getImageByID(id: string): Observable<any> {
const url = `${this.apiUrl}/${id}`;
return this.http.get<Image>(url).pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse): any {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return throwError(
'Something bad happened; please try again later.');
}
}
const multer = require('multer');
const Image = require("../models/image");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
console.log(cb);
cb(null, path.join(__dirname, '../../../../images'));
},
filename: (req, file, cb) => {
var filetype = '';
if(file.mimetype === 'image/gif') {
filetype = 'gif';
}
if(file.mimetype === 'image/png') {
filetype = 'png';
}
if(file.mimetype === 'image/jpeg') {
filetype = 'jpg';
}
cb(null, 'image-' + Date.now() + '.' + filetype);
}
});
const upload = multer({storage: storage});
routes.get('/:id', function(req, res, next) {
Image.findById(req.params.id, function (err, gallery) {
if (err) return next(err);
res.json(gallery);
});
});
// post data
routes.post('/', upload.single('file'), function(req, res, next) {
if(!req.file) {
return res.status(500).send({ message: 'Upload fail'});
} else {
req.body.imageUrl = req.file.filename;
Image.create(req.body, function (err, image) {
if (err) {
console.log(err);
return next(err);
}
res.json(image);
});
}
});