[Dart] Flutter 上传文件
/**
* 请求响应数据
*/
class MsgResponse {
int code; // 状态代码,0 表示没有错误
Object data; // 数据内容,一般为字符串
String errmsg; // 错误消息
MsgResponse([this.code = 0, this.data = null, this.errmsg = ""]);
} static Map _makeHttpHeaders(
[String contentType,
String accept,
String token,
String XRequestWith,
String XMethodOverride]) {
Map headers = new Map<String, String>();
int i = 0; if (!strIsEmpty(contentType)) {
i++;
headers["Content-Type"] = contentType;
} if (!strIsEmpty(accept)) {
i++;
headers["Accept"] = accept;
} if (!strIsEmpty(token)) {
i++;
headers["Authorization"] = "bearer " + token;
} if (!strIsEmpty(XRequestWith)) {
i++;
headers["X-Requested-With"] = XRequestWith;
} if (!strIsEmpty(XMethodOverride)) {
i++;
headers["X-HTTP-Method-Override"] = XMethodOverride;
} if (i == 0) return null;
// print(headers.toString());
return headers;
} /** HTTP POST 上传文件 */
static Future<MsgResponse> httpUploadFile(
final String url,
final File file, {
String accept = "*/*",
String token,
String field = "picture-upload",
String file_contentType, // 默认为null,自动获取
}) async {
try {
List<int> bytes = await file.readAsBytes();
return await httpUploadFileData(url, bytes,
accept: accept,
token: token,
field: field,
file_contentType: file_contentType,
filename: file.path);
} catch (e) {
return new MsgResponse(699, null, e.toString());
}
} /** HTTP POST 上传文件 */
static Future<MsgResponse> httpUploadFileData(
final String url,
final List<int> filedata, {
String accept = "*/*",
String token,
String field = "picture-upload",
String file_contentType, // 默认为null,自动获取
String filename,
}) async {
try {
List<int> bytes = filedata;
var boundary = _boundaryString();
String contentType = 'multipart/form-data; boundary=$boundary';
Map headers =
_makeHttpHeaders(contentType, accept, token); //, "XMLHttpRequest"); // 构造文件字段数据
String data =
'--$boundary\r\nContent-Disposition: form-data; name="$field"; ' +
'filename="${getFileFullName(filename)}"\r\nContent-Type: ' +
'${(file_contentType == null) ? getMediaType(getFileExt(filename).toLowerCase()): file_contentType}\r\n\r\n';
var controller = new StreamController<List<int>>(sync: true);
controller.add(data.codeUnits);
controller.add(bytes);
controller.add("\r\n--$boundary--\r\n".codeUnits); controller.close();
bytes = await new Http.ByteStream(controller.stream).toBytes();
//print("bytes: \r\n" + UTF8.decode(bytes, allowMalformed: true)); Http.Response response =
await Http.post(url, headers: headers, body: bytes);
if (response.statusCode == 200) {
return new MsgResponse(0, response.body);
} else
return new MsgResponse(response.statusCode, response.body);
} catch (e) {
return new MsgResponse(699, null, e.toString());
}
} /** 生成随机字符串 */
static String randomStr(
[int len = 8, List<int> chars = _BOUNDARY_CHARACTERS]) {
var list = new List<int>.generate(
len, (index) => chars[_random.nextInt(chars.length)],
growable: false);
return new String.fromCharCodes(list);
} static const List<int> _BOUNDARY_CHARACTERS = const <int>[
0x30,
0x31,
0x32,
0x33,
0x34,
0x35,
0x36,
0x37,
0x38,
0x39,
0x61,
0x62,
0x63,
0x64,
0x65,
0x66,
0x67,
0x68,
0x69,
0x6A,
0x6B,
0x6C,
0x6D,
0x6E,
0x6F,
0x70,
0x71,
0x72,
0x73,
0x74,
0x75,
0x76,
0x77,
0x78,
0x79,
0x7A,
0x41,
0x42,
0x43,
0x44,
0x45,
0x46,
0x47,
0x48,
0x49,
0x4A,
0x4B,
0x4C,
0x4D,
0x4E,
0x4F,
0x50,
0x51,
0x52,
0x53,
0x54,
0x55,
0x56,
0x57,
0x58,
0x59,
0x5A
];
static const int _BOUNDARY_LENGTH = 48;
static final Random _random = new Random();
static String _boundaryString() {
var prefix = "---DartFormBoundary";
var list = new List<int>.generate(
_BOUNDARY_LENGTH - prefix.length,
(index) =>
_BOUNDARY_CHARACTERS[_random.nextInt(_BOUNDARY_CHARACTERS.length)],
growable: false);
return "$prefix${new String.fromCharCodes(list)}";
} static MediaType getMediaType(final String fileExt) {
switch (fileExt) {
case ".jpg":
case ".jpeg":
case ".jpe":
return new MediaType("image", "jpeg");
case ".png":
return new MediaType("image", "png");
case ".bmp":
return new MediaType("image", "bmp");
case ".gif":
return new MediaType("image", "gif");
case ".json":
return new MediaType("application", "json");
case ".svg":
case ".svgz":
return new MediaType("image", "svg+xml");
case ".mp3":
return new MediaType("audio", "mpeg");
case ".mp4":
return new MediaType("video", "mp4");
case ".htm":
case ".html":
return new MediaType("text", "html");
case ".css":
return new MediaType("text", "css");
case ".csv":
return new MediaType("text", "csv");
case ".txt":
case ".text":
case ".conf":
case ".def":
case ".log":
case ".in":
return new MediaType("text", "plain");
}
return null;
}
[Dart] Flutter 上传文件的更多相关文章
- IE8/9 JQuery.Ajax 上传文件无效
IE8/9 JQuery.Ajax 上传文件有两个限制: 使用 JQuery.Ajax 无法上传文件(因为无法使用 FormData,FormData 是 HTML5 的一个特性,IE8/9 不支持) ...
- 三种上传文件不刷新页面的方法讨论:iframe/FormData/FileReader
发请求有两种方式,一种是用ajax,另一种是用form提交,默认的form提交如果不做处理的话,会使页面重定向.以一个简单的demo做说明: html如下所示,请求的路径action为"up ...
- asp.net mvc 上传文件
转至:http://www.cnblogs.com/fonour/p/ajaxFileUpload.html 0.下载 http://files.cnblogs.com/files/fonour/aj ...
- app端上传文件至服务器后台,web端上传文件存储到服务器
1.android前端发送服务器请求 在spring-mvc.xml 将过滤屏蔽(如果不屏蔽 ,文件流为空) <!-- <bean id="multipartResolver&q ...
- .net FTP上传文件
FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...
- 通过cmd完成FTP上传文件操作
一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...
- 前端之web上传文件的方式
前端之web上传文件的方式 本节内容 web上传文件方式介绍 form上传文件 原生js实现ajax上传文件 jquery实现ajax上传文件 form+iframe构造请求上传文件 1. web上传 ...
- Django session cookie 上传文件、详解
session 在这里先说session 配置URL from django.conf.urls import patterns, include, url from django.contrib i ...
- 4 django系列之HTML通过form标签来同时提交表单内容与上传文件
preface 我们知道提交表单有2种方式,一种直接通过submit页面刷新方法来提交,另一种通过ajax异步局部刷新的方法提交,上回我们说了通过ajax来提交文件到后台,现在说说通过submit来提 ...
随机推荐
- TensorBoard 实践 1
从新查看图的时候,删除旧的logs/下面的文件 tf.scalar_summary('loss',self.loss) AttributeError: 'module' object has no a ...
- Codeforces 1096G. Lucky Tickets【生成函数】
LINK 题目大意 很简单自己看 思路 考虑生成函数(为啥tags里面有一个dp啊) 显然,每一个指数上是否有系数是由数集中是否有这个数决定的 有的话就是1没有就是0 然后求出这个生成函数的\(\fr ...
- HihoCoder - 1501:风格不统一如何写程序
时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi写程序时习惯用蛇形命名法(snake case)为变量起名字,即用下划线将单词连接起来,例如:file_name. ...
- node启动时候报错 Error: Cannot find module 'express'
cmd命令 到目录下,然后运行 npm install -d 再 node hello.js
- (4)格式化输出(%用法和format用法以及区别)
%s用法(%s的用法是写多少个,后面就要传多少个) format用法(基本语法是通过{}和:来代替%.format函数可以接受不限个参数,位置可以不按顺序) 形式一(顺序填坑{}) >>& ...
- Python模块之virtualenvwrapper
Python的virtualenv工具可以创建隔离的Python环境, virtualenvwrapper是virtualenv的进一步封装工具,可以让它更好用. 安装 Linux 系统下: pip ...
- python 判断 txt 编码方式
import chardet f = open('/path/file.txt',r) data = f.read() print(chardet.detect(data)
- TensorFlow笔记-08-过拟合,正则化,matplotlib 区分红蓝点
TensorFlow笔记-08-过拟合,正则化,matplotlib 区分红蓝点 首先提醒一下,第7讲的最后滑动平均的代码已经更新了,代码要比理论重要 今天是过拟合,和正则化,本篇后面可能或更有兴趣, ...
- gitlab-ce-omnibus社区版的备份、还原及升级
gitlab-ce-omnibus社区版的备份和还原,可以使用gitlab自带工具,gitlab-rake来完成,详见下面例子 将旧gitlab服务器备份,并还原至新gitlab服务器 ,这两台git ...
- 使用nat123实现远程桌面
使用nat123实现动态IP或无公网IP时外网访问内网固定端口 使用环境:window7 1.安装nat123软件, 下载地址为 http://www.nat123.com/Pages_2_32.js ...