关于angular:angular-springboot-实现文件上传

Angular

1.html抉择文件

首先写用户点击上传文件的按钮,按本人须要编写,上面只是一个简略的例子

<div class=" row p-3">
    <label class="col-3 text-right col-form-label" >文件<code>*</code></label>
    <input style="display: none"  type="file" class="file-input"
           (change)="onFileSelected($event)" #fileUpload>
    <div class="file-upload  col">
      <button type="button" (click)="fileUpload.click()" class="upload-btn btn-sm btn-success">
        <i class="fas fa-file-image"></i> 抉择文件
      </button>
    </div>
  </div>

用户抉择文件后触发onFileSelected($event)办法,将文件传入c层的办法

2.c层获取文件

onFileSelected(event) {
    const file: File = event.target.files[0];
    if (file) {
      this.file = file;
    }
  }

此时将用户上传的file存在变量file中

文件上传

如果不须要显示进度间接用post办法传输即可

constructor(private httpClient: HttpClient) { }

public saveFile(file:File): Observable<string> {
    formData = new FormData();
    formData.append('file', this.file);
    return this.httpClient.post<string>(`/file`, formData);
  }

要用formdata传file

须要显示进度

const req = new HttpRequest('POST', '/file', formData, {  
  reportProgress: true  
  });  
  
  // 产生一个 event 流  
  return this.http.request(req).subscribe((event: HttpEvent<{}>) => {  
  if (event.type === HttpEventType.UploadProgress) {  
   if (event.total > 0) {  
  // 计算上传的百分比  
  const percent = event.loaded / event.total * 100;  
 } }  });

到此为止,angular的工作就实现了

springboot

应用MultipartFile接口接管文件

@PostMapping("file")
    public String saveFile(@RequestParam("file") MultipartFile file) throws IOException {
        return this.myFileService.saveFile(file);
    }

接管文件之后文件的存储就比较简单了

@Override
    public String saveFile(MultipartFile file) throws IOException {

       String newFileName = UUID.randomUUID().toString()+file.getOriginalFilename();
        File newFile = new File(rootPath+newFileName);
        //定义向数据库中存取的文件门路
        if(!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        file.transferTo(newFile);
        // return file.getOriginalFilename();
        return newFileName;
    }

定义好存储的门路和名称存储就行了,文件名这里用的是UUID,防止反复,对于UUID想要理解请自行查找,留神文件名要加上后缀

留神:如果网站应用了nginx,nginx对传输文件的大小有限度,对于如何批改参考上面文章
nginx批改上传文件大小限度

图片上传与回显

上传与文件上传雷同
回显应用通过URL.createObjectURL(file)这种形式会生成一个拜访本地图片的一个地址

<div class="col">
      <img [src]="sanitizerUrl" class="web-img">
</div>
onFileSelected(event) {
    const file: File = event.target.files[0];
    if (file) {
      this.canSubmit = false;
      const formData = new FormData();
      formData.append('thumbnail', file);
      this.picture = file;
      let imgUrl = window.URL.createObjectURL(file);
      this.sanitizerUrl = this.sanitizer.bypassSecurityTrustUrl(imgUrl);
    }
  }

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理