參考資料:
http://www.imooc.com/article/40038
https://github.com/xkeshi/image-compressor
示例代碼:
<nz-upload class="avatar-uploader" [nzAccept]="'image/*'" nzFileType="image/png,image/jpeg,image/gif,image/jpg" [nzAction]="uploadPictureUrl" nzName="avatar" nzListType="picture-card" [nzShowUploadList]="false" [nzCustomRequest]="uploadImp" (nzChange)="handleChange($event)"> <ng-container *ngIf="!imageUrl"> <i nz-icon nzType="picture" nzTheme="outline"></i> <div class="ant-upload-text">上傳</div> </ng-container> <img *ngIf="imageUrl" [src]="imageUrl" class="avatar" style="width:100px;height: 100px;"> </nz-upload> <p>請上傳jpg, gif, png格式的圖片。建議圖片尺寸 寬:90px;高:90px</p>
import ImageCompressor from 'image-compressor.js'
// 自定義上傳方法的實現 uploadImp = async (item) => { debugger const isJPG = item.file.type.indexOf('image') > -1; if (!isJPG) { this.message.error('只能上傳圖片文件!'); return; } // 進行圖片壓縮 const compressionFile = await new ImageCompressor().compress(item.file, { quality: .8, maxWidth: 1000, maxHeight: 1000, convertSize: 614400, //超過600kb壓縮 success(result) { }, error(e) { console.log(e); debugger throw { message: `壓縮失敗${e.message}` } } }).then(ret => { debugger console.log(ret); item.file = ret; if (ret.size > 600 * 1024) throw { message: '壓縮后的圖片不能超過600KB' }; const formData = new FormData(); formData.append('file', item.file, item.file.name); this.http.post(this.uploadPictureUrl, formData).subscribe(result => { debugger }); }).catch((err) => { const msg = err.message ? err.message : err; this.message.error(`圖片上傳失敗,請重試:${msg}`); }); }
public string UploadImgToOss() { var file = Request.Form.Files.FirstOrDefault(); if (file == null) throw new UserFriendlyException(L("FileInfo_Change_Error")); var fileInfo = new FileInfo(file.FileName); var fileExt = Path.GetExtension(file.FileName); byte[] fileBytes; string url = ""; using (var stream = file.OpenReadStream()) { fileBytes = stream.GetAllBytes(); if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new UserFriendlyException("請上傳圖片文件,僅接受Jpg、PNG、Gif三種格式!"); } var upLoadPath = "/Upload/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/"; var newFileName = $"{DateTime.Now:yyyyMMddHHmmss}_{Guid.NewGuid():n}_{fileExt}"; var data = new MemoryStream(fileBytes); var result = OssDrive.UpLoad(newFileName, data); if (!result.Status) { throw new UserFriendlyException(result.Message); } url = "http://" + result.Data.Url; } return url; }