Angular中使用drag and drop实现文件拖拽上传,及flask后端接收

效果:拖拽文件到组件上面时 边框变大变红 松手后发送到服务器(或者点击蓝字手动选择文件)并且把文件名显示在框内,美化还没做




html

html 复制代码
<div class="drapBox">
    <div id="drop" (dragenter)="dragenter($event)" (dragover)="dragover($event)" (dragleave)="dragleave($event)"
        on-drop="drop($event)" [ngClass]="{'dragover':isdragover,'notdragover':!isdragover}">
        <div class="desc">Drag files here, or</div>
        <label for="file" class="input_desc">
            <input class="drag-message-input" type="file" id="file" name="file" on-change="inputFile($event)" />
            <span class="drag-message-manual">click to select</span>
        </label>
    </div>
    <div id="selectedFilesBox" class="absflex" *ngIf="selectedFilesName.length>0">
        <div class="allFileDesc">{{selectedFilesCount}} files selected:</div> 
        <div class="fileDesc" *ngFor="let item of selectedFilesName">{{item}}</div>
    </div>
</div>

Ts

javascript 复制代码
import { Component } from '@angular/core';
import { Observable, catchError, of, switchMap } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-filedrag',
  templateUrl: './filedrag.component.html',
  styleUrls: ['./filedrag.component.css']
})
export class FiledragComponent {
  isdragover:boolean=false;
  selectedFilesName:string[]=[];
  selectedFilesCount:number = 0;
  constructor(private http: HttpClient){}
  dragover(e:Event){
    e.stopPropagation();
    e.preventDefault();
    this.isdragover=true;
    console.log("dragover");
  }
  dragleave(e:Event){
    e.stopPropagation();
    e.preventDefault();
    this.isdragover=false;
    console.log("dragleave");
  }
  dragenter(e:Event){
    e.stopPropagation();
    e.preventDefault();
    console.log("dragenter");
  }
  drop(e:any){
   e.stopPropagation();
   e.preventDefault();
   this.isdragover=false;
   let dataTransfer=e.dataTransfer;
   let files=dataTransfer.files;
   console.log("files:");
   console.log(files);
   this.showSelectedFiles(files);
   this.handleFiles(files).subscribe();
 }
 inputFile(e:any){
  console.log(e.target.files);
  this.showSelectedFiles(e.target.files);
  this.handleFiles(e.target.files).subscribe();
}
showSelectedFiles(files: FileList): void{
  this.selectedFilesName = [];
  this.selectedFilesCount = files.length;
  for(let i=0;i<files.length;i++){
    this.selectedFilesName.push(files[i].name);
  }

}
handleFiles(filesToUp: FileList): Observable<{message:string}> {
  const url: string = "http://127.0.0.1:5000/up_file";
  const formData: FormData = new FormData();
  for(let i=0;i<filesToUp.length;i++){
    formData.append('files', filesToUp[i]);
  }
  return this.http
    .post<any>(url, formData).pipe(
      switchMap((res: {message:string}) => { console.log(res); return of(res); }),
      catchError(er=>{console.log(er);return of({message:"error"})})
    );
}

}

Css

css 复制代码
.drapBox{
    position: relative;
    width: 300px;
    height: 300px;
}
#drop {
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;

}
.dragover{
    border: 2px dashed red;
    zoom:108%;
}
.notdragover{
    border: 2px dashed grey;
}


#file {
    display: none;
}
.desc{
    font-size: 1rem;
}
.input_desc {
    padding-left: 5px;
    font-size: 1rem;
    color: #4b87ff;
    cursor: pointer;
}
.absflex{
    position: absolute;
    width: 100%;
    height: 100%;
}
.allFileDesc{
    padding: 5px;
}
.fileDesc{
    display: inline-block;
    padding: 5px;
    border: 1px solid #4b87ff;
    font-style: italic;
    width: auto;
    height: 20px;
}

后端python flask代码一起贴上

python 复制代码
# -*- coding: utf-8 -*-
from flask import Flask,request
from flask import send_from_directory,render_template
from flask_cors import CORS

# r'/*' 是通配符,让本服务器所有的URL都允许跨域请求

app = Flask(__name__)
CORS(app, resources=r'/*')
@app.route("/up_file", methods=["POST", "GET"])
def file_receive():
    # try:
    files = request.files.getlist("files")
    print(files)
    if files is None:  # 表示没有发送文件
        return {
            'message': "failed"
        }
    else:
        return {
                   'message': "success"
        }
if __name__ == '__main__':
    app.run(debug=True)
相关推荐
怕浪猫2 分钟前
Electron 开发实战(十六):总结与展望|生态现状、框架对比、行业趋势与学习指南
前端·javascript·electron
文心快码BaiduComate2 分钟前
Comate 搭载GLM-5.2:百万上下文,稳定支撑长程任务
前端·程序员·开源
星栈13 分钟前
Dioxus 的 `rsx!` 语法:如果你会 React,上手确实特别快
前端·前端框架
Momo__14 分钟前
TypeScript NoInfer<T>——精准控制泛型推断的工具类型
前端·typescript
巴勒个啦19 分钟前
Pinia 源码解析:响应式状态管理是如何工作的
angular.js
lichenyang4531 小时前
从 Web 容器开始,理解 ASCF 元服务开发
前端
用户059540174461 小时前
把待办应用从Electron换成Tauri,内存占用狂降90%,打包体积仅5MB
前端·css
假如让我当三天老蒯1 小时前
回归基本功!前端的解构赋值、扩展运算符、剩余参数
前端·面试
bonechips2 小时前
JS 数组指南:从内存原理到二维矩阵
前端·javascript