首页 > 解决方案 > 如何在 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 表

在此处输入图像描述

标签: phpmysqlflutter

解决方案


这是我用来将图像上传到数据库的解决方案。基本上,我使用图像路径保存到 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 文件夹中:

在此处输入图像描述


推荐阅读