我试图使用ngx-image-cropper在我的应用程序上上传图像,但是我无法保存被裁剪的图像。例如,如果我试图保存主文件(通过input type="file"加载的文件),一切都正常。在这种情况下,文件的发送方式如下:
{name: "300_3.jpg",
lastModified: 1510510128437,
lastModifiedDate: Sun Nov 12 2017 20:08:48 GMT+0200 (GTB Standard Time), webkitRelativePath: "",
size: 81972, …}但是,如果我试图上传该图像的裁剪版本,文件如下所示:
data:image/png;base64,iVBORw0KGgoAAAANSU............来自服务器的响应类似于:
{error: "Bad Request",
exception:"org.springframework.web.multipart.support.MissingServletRequestPartException",
message: "Required request part 'file' is not present",
path: "/api/myEndPoint/",
status: 400,
timestamp: 1518424822285}因此,基本上我需要像第一种情况那样发送一个可怜虫,但我所拥有的只是一个base64项目。
这里还有HTML代码,以防有帮助:
<image-cropper
[imageChangedEvent]="imageChangedEvent"
[maintainAspectRatio]="true"
[aspectRatio]="4 / 4"
[resizeToWidth]="250"
format="png"
(imageCropped)="imageCropped($event)"
(imageLoaded)="imageLoaded()"
(loadImageFailed)="loadImageFailed()"
*ngIf="isUploadedFile">
</image-cropper>有人能告诉我如何上传裁剪版本,而不是我上传的初始文件吗?或者这是需要在服务器上修复的东西,所以它可以接受我发送的文件吗?谢谢!
发布于 2018-02-12 09:36:00
那根绳子:
data:image/png;base64,iVBORw0KGgoAAAANSU............意味着您有您的裁剪图像作为dataURI。如果您想要将裁剪图像的上传工作起来,那么您应该将其从dataURI转换为Blob。如果您已经这样做了,那么您可以从Blob创建一个File并将其上传到服务器。
下面是一个将dataURI转换为Blob的函数
dataURItoBlob(dataURI): Blob {
const byteString = atob(dataURI.split(',')[1]);
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
const ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: mimeString });
}现在您可以创建File并将其上传到服务器。下面是uplaod函数的一个示例:
uploadAttachmentToServer() {
const fileToUpload: File = new File([this.dataURItoBlob(yourCroppedImage)], 'filename.png');
this.attachmentService.postAttachment(fileToUpload).subscribe(data => {
// success, do something
}, error => {
// failure, do something
});
}发布于 2018-08-12 07:41:21
实际上,ngx-图像-裁剪器提供了一个属性imageCroppedFile,它为您提供转换为Blob的裁剪图像,例如在html中:
<image-cropper
[imageChangedEvent]="imageChangedEvent"
...
(imageCroppedFile)="fileCropped($event)">
</image-cropper>然后,在组件中,您可以从Blob转换为File:
fileCropped(blob: Blob) {
const file = new File([blob], 'image.png');
// upload the file
}发布于 2021-01-02 01:45:15
附带一个base64ToFile函数,该函数返回Blob对象.
import { ImageCropperedEvent, base64Tofile } from 'ngx-image-cropper'您的代码应该如下所示:
someFunction(): File {
// Assuming you have stored the event.base64 in an instance variable 'croppedImage'
const file: File = new File([base64ToFile(this.croppedImage)], 'fileName.png');
return file;
}https://stackoverflow.com/questions/48742455
复制相似问题