我应该如何配置托管服务器以从 Flutter 应用程序上传文件?

问题描述 投票:0回答:1

我想为我的 Flutter 移动应用程序创建一个文件目录并上传文件(任何类型的图像或 pdf 文件)。

我使用以下代码来选择文件并将其上传到服务器:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:file_picker/file_picker.dart';

class fileUpload extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: UploadScreen(),
    );
  }
}

class UploadScreen extends StatefulWidget {
  @override
  _UploadScreenState createState() => _UploadScreenState();
}

class _UploadScreenState extends State<UploadScreen> {
  File? _selectedFile;

  Future<void> _selectFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      setState(() {
        _selectedFile = File(result.files.single.path!);
      });
    }
  }

  Future<void> _uploadFile() async {
    if (_selectedFile == null) {
      print('no files picked');
      return;
    }

    var uri = Uri.parse('http://myhostingdomain.com/specialdirectory'); // Sunucunun URL'si

    var request = http.MultipartRequest('POST', uri);
    request.files.add(await http.MultipartFile.fromPath('file', _selectedFile!.path));

    var response = await request.send();
    if (response.statusCode == 200) {
      print('successfully uploaded.');
    } else {
      print('Error returned: ${response.reasonPhrase}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sample file upload page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: _selectFile,
              child: Text('Choose a file'),
            ),
            SizedBox(height: 20),
            _selectedFile != null
                ? Text('selected file: ${_selectedFile!.path}')
                : Text('no files found'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _uploadFile,
              child: Text('upload the file'),
            ),
          ],
        ),
      ),
    );
  }
}

当我运行我的移动应用程序时,所有内容看起来都是文件,并且文件似乎已上传。但是当我检查托管目的地的文件服务器时,没有上传文件。

我相信在开始上传文件之前我必须配置公共托管服务器并发送身份验证。

我应该如何更新代码以在连接目标时添加凭据,另外我应该如何配置托管服务器以接受上传?

谢谢你

我在互联网上找到了几种解决方案,但不包括公共托管服务器的凭据。

flutter file-upload server configuration
1个回答
0
投票

上传文件是一个多步骤的过程,需要在客户端和服务器端进行工作:

服务器端:

创建一个文件夹来保存上传的文件。确保该文件夹位于您的网站目录中,您可以将其命名为:UploadsFolder

对于本示例,我使用的是 localhost。

将以下代码写入php文件并命名为uploadData.php

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {

        // File handling
        $file = $_FILES['file'];
        $fileName = $file['name'];
        $fileTmpName = $file['tmp_name'];
        

        // Move the uploaded file to the desired directory
        $uploadsDirectory = 'UploadsFolder/';
        $targetPath = $uploadsDirectory . $fileName;

        move_uploaded_file($fileTmpName, $targetPath);

  
    } catch (Exception $e) {
        http_response_code(500); // Internal Server Error
    } 
}
?>

客户端:

在终端中写入以下命令以在 flutter 中安装 Dio 和 file_picker 包:

flutter 酒吧添加 dio
flutter pub 添加 file_picker

使用以下代码上传您的文件

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:dio/dio.dart';

void main()=>runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: 
        Center(child:
        FileUploader()
      )),
    );
  }
}
// as widgets

class FileUploader extends StatefulWidget {
  const FileUploader({super.key});
  @override
  State<FileUploader> createState() => _FileUploaderState();
}

class _FileUploaderState extends State<FileUploader> {
String? fileName;
PlatformFile? selectedFile;


Future<void> uploadFileToServer() async {
  try {
    Dio dio = Dio();

    // Set your localhost server URL
    const String apiUrl = "http://10.0.2.2/demoProject/uploadData.php";

    // Create FormData object
    FormData formData = FormData.fromMap({
    'file': await MultipartFile.fromFile(selectedFile!.path??""),
      // You can add additional data as needed
      
    });

    // Send POST request with FormData
    Response response = await dio.post(apiUrl, data: formData);

    // Check if the request was successful (status code 200)
    if (response.statusCode == 200) {
    print('File uploaded successfully');
  
    } else {
      print('File upload failed with status ${response.statusCode}');
    }
    
  } catch (error) {
    print('Error uploading file: $error');
  }
 
}

pickFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      PlatformFile? file = result.files.first;
    setState(() {
      selectedFile=file;
      fileName=file.name;
print("fileName is $fileName");
    });
    }
    return null;
  }  
  
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
      
ElevatedButton(onPressed: () async {
await pickFile();


}, child: const Text("Pick file to upload")),

ElevatedButton(onPressed: ()async{
if(selectedFile!=null){
    
uploadFileToServer();

}
}, child: const Text("Upload selected file"))

    ],);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.