如何使用php上传文件夹中的颤音图像?

发布于 2025-02-12 06:29:18 字数 5760 浏览 1 评论 0原文

我想在PHP中使用API​​在文件夹中上传图像,但我认为Flutter无法将图像发送为文件类型,而PHP无法在服务器中的文件夹中上传图像。
请帮助我HW可以在文件夹中上传图像,

这是我的代码: -

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.
);
}
}

请帮助如何上传扑波图像,以便我可以理解Fluter文件系统。

这是我的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);
    }

任何人都会颤抖的开发人员,请帮助我了解此文件系统。

I want to upload image in folder with API in php but i think flutter cannot send image as file type and php can't upload image in folder in server.
Please help me hw can i upload image in folder

here is my code :-

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.
);
}
}

Please help how can I upload the flutter Image so I can understand the fluter file system.

here is my php code:-

    $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);
    }

anyone flutter developer please help me to understand this file system.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾铮苏瑾 2025-02-19 06:29:20
 String uploadurl = "http://192.168.0.112/test/image_upload.php";
 //dont use http://localhost , because emulator don't get that address
 //insted use your local IP address or use live URL
 //hit "ipconfig" in windows or "ip a" in linux to get you local IP

try{
  List<int> imageBytes = uploadimage.readAsBytesSync();
  String baseimage = base64Encode(imageBytes);
  //convert file image to Base64 encoding
  var response = await http.post(
          uploadurl, 
          body: {
             'image': baseimage,
          }
  );
  if(response.statusCode == 200){
     var jsondata = json.decode(response.body); //decode json data
     if(jsondata["error"]){ //check error sent from server
         print(jsondata["msg"]);
         //if error return from server, show message from server
     }else{
         print("Upload successful");
     }
  }else{
    print("Error during connection to server");
    //there is error during connecting to server,
    //status code might be 404 = url not found
  }

注意:上载图是皮卡图函数中的PickedFile变量。

 String uploadurl = "http://192.168.0.112/test/image_upload.php";
 //dont use http://localhost , because emulator don't get that address
 //insted use your local IP address or use live URL
 //hit "ipconfig" in windows or "ip a" in linux to get you local IP

try{
  List<int> imageBytes = uploadimage.readAsBytesSync();
  String baseimage = base64Encode(imageBytes);
  //convert file image to Base64 encoding
  var response = await http.post(
          uploadurl, 
          body: {
             'image': baseimage,
          }
  );
  if(response.statusCode == 200){
     var jsondata = json.decode(response.body); //decode json data
     if(jsondata["error"]){ //check error sent from server
         print(jsondata["msg"]);
         //if error return from server, show message from server
     }else{
         print("Upload successful");
     }
  }else{
    print("Error during connection to server");
    //there is error during connecting to server,
    //status code might be 404 = url not found
  }

NOTE: uploadimage is the pickedFile variable in pickimage function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文