当前位置: 首页 > news >正文

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

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

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

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

.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代码一起贴上

# -*- 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)
http://www.lryc.cn/news/142529.html

相关文章:

  • Spring Authorization Server入门 (十六) Spring Cloud Gateway对接认证服务
  • 配置Flink
  • 39、springboot的前端静态资源的WebJar支持(bootstrap、jquery等)及自定义图标和首页
  • 【图论】缩点的综合应用(一)
  • C++—纯虚函数
  • 经过卷积神经网络之后的图片的尺寸如何计算
  • Java升级JDK17(更高版本同理),修改maven
  • Go测试之.golden 文件
  • 回归预测 | MATLAB实现GA-RF遗传算法优化随机森林算法多输入单输出回归预测(多指标,多图)
  • springboot整合rabbitmq死信队列
  • 高中信息技术教资考试模拟卷(22下)
  • Linux中shadow及passwd格式内容解析
  • 计算机视觉 – Computer Vision | CV
  • 2.Redis 通用命令
  • 【学习FreeRTOS】第18章——FreeRTOS软件定时器
  • C++--两个数组的dp问题(2)
  • 利用人工智能彻底改变库存管理:综合指南
  • 连接器信号完整性仿真教程 七
  • Wireshark数据抓包分析之UDP协议
  • Java小游戏
  • 服务器Linux系统配置mysql数据库主从自动备份
  • Java通过PowerMockito和Mokito进行单元测试
  • 数字化技术无限延伸,VR全景点亮智慧生活
  • 抖音艺术签名小程序源码/艺术签名设计小程序源码/字节跳动小程序开发
  • 养号自动化,指纹浏览器和RPA机器人解除烦恼
  • ES6中promise的使用
  • 前端如何走通后端接口
  • iOS swift5 扫描二维码
  • 【马拉车算法/动态规划】最长回文字串
  • 什么是 fail-fast? 什么是fail-safe?