php - 如何在 MySQL 中使用 Flutter 和 php 上传图片
问题描述
我想问如何使用 post 方法将图像文件发布到 MySQL?因为我所做的只是上传文件路径而不是图像。
我的帖子请求:
Future addProduct() async{
var url = 'http://10.0.2.2/foodsystem/addproduct.php';
http.post(url, body: {
"productname": controllerName.text,
"productprice": controllerPrice.text,
"producttype": controllerType.text,
"product_owner": globals.userId,
"image": _image.path,
//"image": _image.path.split('/').last,
});
我的 PHP 代码:
<?php
include 'conn.php';
$product_owner = $_POST['product_owner'];
$productname = $_POST['productname'];
$productprice = $_POST['productprice'];
$producttype = $_POST['producttype'];
$image = $_POST['image'];
//$realImage = base64_decode($image);
$connect->query("INSERT INTO product (product_name, product_price, product_type, product_owner, image) VALUES
('".$productname."','".$productprice."','".$producttype."','".$product_owner."','".$image."')")
?>
我的 MySQL 表
解决方案
这是我用来将图像上传到数据库的解决方案。基本上,我使用图像路径保存到 MySQL。然后图像本身我将它保存在 htdoc 文件夹中并且它可以工作。
Flutter代码:(需要先导入重要库)
import "package:async/async.dart";
import 'package:path/path.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
Future addProduct(File imageFile) async{
// ignore: deprecated_member_use
var stream= new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length= await imageFile.length();
var uri = Uri.parse("http://10.0.2.2/foodsystem/uploadg.php");
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile("image", stream, length, filename: basename(imageFile.path));
request.files.add(multipartFile);
request.fields['productname'] = controllerName.text;
request.fields['productprice'] = controllerPrice.text;
request.fields['producttype'] = controllerType.text;
request.fields['product_owner'] = globals.restaurantId;
var respond = await request.send();
if(respond.statusCode==200){
print("Image Uploaded");
}else{
print("Upload Failed");
}
PHP代码:
<?php
include 'conn.php';
$image = $_FILES['image']['name'];
$product_owner = $_POST['product_owner'];
$productname = $_POST['productname'];
$productprice = $_POST['productprice'];
$producttype = $_POST['producttype'];
$imagePath = "uploads/".$image;
move_uploaded_file($_FILES['image']['tmp_name'],$imagePath);
$connect->query("INSERT INTO product (product_name, product_price, product_type, product_owner, image) VALUES ('".$productname."','".$productprice."','".$producttype."','".$product_owner."','".$image."')");
//$connect->query("INSERT INTO product (product_name,image) VALUES ('".$productname."','".$image."')");
?>
在 MySQL 中的结果:
结果在 htdoc 文件夹中:
推荐阅读
- react-native - 删除 npm 依赖项后重建 react-native 应用程序时出现“找不到项目”错误
- database - 如何在没有 Web 服务器的情况下查看 H2 创建的 database.mv.db 文件
- search - 使用按钮更改搜索表单
- sql - 计算带有子查询的行数的比率
- python - 使用 python 在文件夹和子文件夹中创建 .pyd 文件
- ibm-cloud - 使用端口 80 部署标准容器时,IBM Cloud Code Engine 修订失败
- python - 从波形文件计算具有定义的 FFT 长度、块大小和窗口的 FFT
- reactjs - 从 React 中的不同函数获取字符串
- sparql - 使用 rdf4j 构造 sparql 查询
- reactjs - 我可以在函数中使用 React.lazy 吗?