flutter 如何上传本地文件
时间: 2023-07-03 14:10:02 浏览: 74
要在Flutter中上传本地文件,您需要使用Flutter中提供的dart:io库。首先,使用FilePicker库选择要上传的文件。然后,使用http包中的MultipartRequest,将文件作为多部分请求附加到请求体中。最后,使用http包中的HttpClient将请求发送到服务器。以下是一个示例代码:
```dart
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
class FileUpload extends StatefulWidget {
@override
_FileUploadState createState() => _FileUploadState();
}
class _FileUploadState extends State<FileUpload> {
File file;
void _openFileExplorer() async {
file = await FilePicker.getFile(type: FileType.any);
setState(() {});
}
Future _uploadFile() async {
var request = http.MultipartRequest(
'POST',
Uri.parse('your-upload-api-url-here'),
);
request.files.add(await http.MultipartFile.fromPath('file', file.path));
request.headers.addAll({'Authorization': 'Bearer your_access_token_here'});
var response = await request.send();
if (response.statusCode == 200) {
// handle success
} else {
// handle error
}
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
FlatButton(
onPressed: _openFileExplorer,
child: Text('Select File'),
),
file != null ? Text(file.path) : Container(),
RaisedButton(
onPressed: _uploadFile,
child: Text('Upload File'),
),
],
);
}
}
```
您需要将“your-upload-api-url-here”替换为您的上传API的实际URL,“Bearer your_access_token_here”替换为您的实际访问令牌。此外,您需要在pubspec.yaml文件中添加依赖项file_picker和http。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)