angular - 角度上传图片到服务器
问题描述
我是新来的。实际上,我需要知道如何将图像上传到服务器。因为当我尝试上传时,我得到了这个错误。
这是我的代码
HTML
<input type="file" name="files" (change)="fileUpload($event)" accept='image/gif' />
零件
fileUpload(event:any){
this.image = event.target.files[0].name;
let itemCode = this.activatedRoute.snapshot.paramMap.get('id');
return this.http.post(environment.apiBaseUrl + environment.path + '/data/uploadgif', {file: this.image, menuCode: itemCode})
.subscribe((data) => {
if(data['status']['code'] === 0) {
document.location.href = environment.url;
} else {
}
});
}
希望大家能帮助我提前谢谢
解决方案
这是上传图像的简单方法。
function handleInputChange(e) {
var file = e.dataTransfer ? e.dataTransfer.files[0] : e.target.files[0];
var pattern = /image-*/;
var reader = new FileReader();
if (!file.type.match(pattern)) {
alert('invalid format');
return;
}
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsDataURL(file);
}
function _handleReaderLoaded(e) {
let reader = e.target;
const result = reader.result;
// this.openSnackBar(result.length,"OK")
if (!result) {
this.openSnackBar("Cannot read", "OK")
this.imageSrc = '';
}
if (result.length > 400000) {
this.openSnackBar("File size should be less than 300KB", "OK")
this.imageSrc = '';
}
else {
this.imageSrc = reader.result;
}
}
<input type="file" id="fileupload" (change)="handleInputChange($event)">
<label for="fileupload" class="custom-file-upload">
<mat-icon style="font-size: large; vertical-align: middle;">attach_file</mat-icon>
Select</label>
所以你必须基本上将图像转换为base64,然后上传到服务器。multer
如果您nodejs
用作服务器,则可以使用。
推荐阅读
- ruby - 似乎无法运行 ruby 2.6.0 自制版本 - 总是引用系统 ruby 2.3.0
- c# - 将数据从模型导入视图给我一个我无法解决的错误
- reactjs - 抓取 Google 显示空白页 - Reactjs
- java - 如何等待短信发送确认,然后发送下一条短信 Android
- javascript - 在 javascript 中读取 iFrame(不在同一域 - YouTube)中的 div 状态
- git - SVN 到 Git 迁移:将选定的一组提交移动到新存储库
- python - 如何将第二轴添加到 holoviews 的散景图中?
- python - 如何使用熊猫从字符串中删除小数点
- node.js - winston 'handleExceptions: true' 记录两次
- maven - 无法执行 SonarQube:无法从服务器获取引导索引: