clent端使用angular组件
upload_component.html
form id="myForm" method="POST" enctype="multipart/form-data"> { {progress}}
upload_component.dart
import 'package:angular/angular.dart';import 'package:angular_forms/angular_forms.dart';import "dart:html";@Component( selector: 'upload', templateUrl: 'upload_component.html', styleUrls: const ['upload_component.css'], directives: const [CORE_DIRECTIVES,formDirectives],)class UploadComponent{ //表示文件上传进度 String progress; void upload(){ // formDate 表示用于存储html文件表单字段的对象 var formData = new FormData(querySelector("#myForm")); final request = new HttpRequest(); //使用post方法 request.open('POST', 'http://localhost:8080/upload'); //监听文件上传进度 request.upload.onProgress.listen((ProgressEvent e) { progress = (e.loaded*100/e.total).toInt().toString() + '%'; }); //监听文件上传完成时调用 request.onLoad.listen((e) { print('Uploaded'+request.response); }); request.send(formData); }}
server端
import 'dart:io';import 'package:mime/mime.dart';import 'package:shelf/shelf.dart';import 'package:shelf/shelf_io.dart' as io;import 'package:shelf_cors/shelf_cors.dart';import 'package:shelf_rest/shelf_rest.dart';void main() { var rootRouter = router()..post('/upload',(Request request) async{ print(request.headers); var header = HeaderValue.parse(request.headers['content-type']); await for(MimeMultipart part in request.read().transform(new MimeMultipartTransformer(header.parameters['boundary']))) { if(part.headers.containsKey('content-disposition')) { header = HeaderValue.parse(part.headers['content-disposition']); String filename = header.parameters['filename']; final file = new File(filename); IOSink fileSink = file.openWrite(); await part.pipe(fileSink); fileSink.close(); } } return new Response.ok("Success",headers:{'Access-Control-Allow-Origin':'*'}); }); //通过此中间件设置跨域标头信息 final cors = createCorsHeadersMiddleware( corsHeaders: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'Authorization, Content-Type', 'Access-Control-Allow-Headers': 'Authorization, Origin, X-Requested-With, Content-Type, Accept', 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE' } ); var handler = const Pipeline() .addMiddleware(logRequests()) .addMiddleware(cors) .addHandler(rootRouter.handler); printRoutes(rootRouter); io.serve(handler, 'localhost', 8080).then((server) { print('Serving at http://${server.address.host}:${server.port}'); });}