【发布时间】:2022-08-10 15:11:46
【问题描述】:
我想在 php 中使用 API 上传文件夹中的图像,但我认为 Flutter 无法将图像作为文件类型发送,并且 php 无法在服务器的文件夹中上传图像。
请帮助我如何在文件夹中上传图像
这是我的代码:-
import \'dart:convert\';
import \'package:flutter/material.dart\';
import \'package:image_picker/image_picker.dart\';
import \'package:http/http.dart\' as http;
import \'dart:io\';
import \'package:http_parser/http_parser.dart\';
void main() {
runApp(Upload());
}
class Upload extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: \'Flutter Image\',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyImagePicker(title: \'Upload image\'),
);
}
}
class MyImagePicker extends StatefulWidget {
MyImagePicker({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyImagePickerState createState() => _MyImagePickerState();
}
class _MyImagePickerState extends State<MyImagePicker> {
PickedFile? _imageFile;
final String uploadUrl = \'https://www.*******.net/index.php?act=proPicUpdate\';
final ImagePicker _picker = ImagePicker();
//var url = http.get(Uri.https(\'www.*******.net\', \'/index.php\',
{\'act\':\'pages\',\'UsrID\': \'${UsrID}\'}));
Future<String?> uploadImage(String filepath, url) async {
var request = http.MultipartRequest(\'POST\', Uri.parse(url));
print(request);
String fileName = filepath.split(\'/\').last;
print(fileName);
request.files.add(await http.MultipartFile.fromPath(\'image\', fileName, contentType: MediaType(\'image\',\'jpeg\')));
print(request);
// request.files.add(http.MultipartFile.fromBytes(\'image\', await File.fromUri(filepath).readAsBytes(), contentType: MediaType(\'image\',\'jpeg\')));
var res = await request.send();
//print(res.reasonPhrase);
final respStr = await res.stream.bytesToString();
print(respStr);
return res.reasonPhrase;
}
Future<void> retriveLostData() async {
final LostData response = await _picker.getLostData();
if (response.isEmpty) {
return;
}
if (response.file != null) {
setState(() {
_imageFile = response.file;
});
} else {
print(\'Retrieve error ${response.exception?.code}\');
}
}
Widget _previewImage() {
final _imageFile = this._imageFile;
if (_imageFile != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.file(File(_imageFile.path)),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () async {
var res = await uploadImage(_imageFile.path, uploadUrl);
print(res);
},
child: const Text(\'Upload\'),
)
],
),
);
} else {
return const Text(
\'You have not yet picked an image.\',
textAlign: TextAlign.center,
);
}
}
void _pickImage() async {
try {
final pickedFile = await _picker.getImage(source: ImageSource.gallery);
setState(() {
_imageFile = pickedFile;
});
} catch (e) {
//print(\"Image picker error ${e!}\");
print(\"Image picker error\");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FutureBuilder<void>(
future: retriveLostData(),
builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return const Text(\'Picked an image\');
case ConnectionState.done:
return _previewImage();
default:
return const Text(\'Picked an image\');
}
},
)),
floatingActionButton: FloatingActionButton(
onPressed: _pickImage,
tooltip: \'Pick Image from a gallery\',
child: Icon(Icons.photo_library),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
请帮助我如何上传颤振图像,以便我了解颤振文件系统。
这是我的php代码:-
$Status = [];
$error = [];
if(isset($_REQUEST)){
//$imagename = $_FILES[\'image\'][\'name\'];
$imagename = filter_input(INPUT_GET, \'image\', FILTER_SANITIZE_STRING);
$extension = pathinfo($imagename, PATHINFO_EXTENSION);
//echo $imagename;
//echo $extension;
if($extension==\'JPG\' || $extension==\'jpg\' || $extension==\'jpeg\' || $extension==\'png\')
{
//$tmpFilePath = $imagename;
//if ($tmpFilePath != \"\"){
//Setup our new file path
echo $location = __DIR__. \'/images/\' .$image;
$newFilePath = $location;
if(move_uploaded_file($image, $newFilePath))
{
//include_once(\"inc/resize-class.php\");
//$resizeObj = new resize($newFilePath);
//$resizeObj -> resizeImage(720, 720, \'auto\');
//$resizeObj -> saveImage($newFilePath, 100);
//$newFilePath = watermarkImage($newFilePath);
$Status[\'status\'] = \"success\";
//$data[\'errors\'] = \"Success! Image ($count) Uploaded Successfully\";
$error[] = \"Upload success\";
}
else {
$Status[\'status\'] = \"error\";
$error[] = \"Failed: File can not be moved to loaction\";
}
}//if EXTERSION ENDS
else {
$Status[\'status\'] = \"error\";
$error[] = \"Invalid file format\";
}
$Status[\'error\']=$error;
print json_encode($Status);
}
任何颤振开发人员请帮助我理解这个文件系统。
标签: php flutter flutter-layout flutter-dependencies flutter-image