廊坊阿里云代理商:android php 上传文件到服务器

在Android应用中,可以用以下代码将文件上传到服务器。

首先在Android前端编写一个文件上传页面,其中包含一个文件选择框和一个上传按钮。

代码如下:

<!-- 文件选择框 -->
<input type="file" id="file" name="file" />

<!-- 上传按钮 -->
<button type="button" onclick="uploadFile()">上传文件</button>

然后,编写一个上传函数 uploadFile() ,使用 HttpUrlConnection 发送 POST 请求将所选的文件上传到服务器。

代码如下:

private void uploadFile() {

    try {
        // 获取所选的文件
        String filePath = getRealPathFromURI(getApplicationContext(), fileUri);
        File file = new File(filePath);

        // 设置上传地址
        String uploadUrl = "http://your-server.com/upload.php";

        // 创建请求
        URL url = new URL(uploadUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        // 设置请求头
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Charset", "UTF-8");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        // 创建输出流
        DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + end);
        dos.writeBytes("Content-Disposition: form-data; name="file";filename="" + file.getName() + """ + end);
        dos.writeBytes(end);

        // 创建输入流
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[8192];
        int count = 0;
        while ((count = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, count);
        }
        fis.close();

        // 添加结尾
        dos.writeBytes(end);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + end);

        // 发送请求并获取响应
        dos.flush();
        InputStream is = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String result = br.readLine();
        dos.close();
        is.close();

        // 显示上传结果
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
        // 显示上传失败消息
        Toast.makeText(getApplicationContext(), "文件上传失败", Toast.LENGTH_SHORT).show();
    }
}

// 获取文件真实路径
public String getRealPathFromURI(Context context, Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        cursor.close();
        return path;
    }

最后,将文件上传到服务器的 PHP 脚本如下:

<?php
if ($_FILES["file"]["error"] > 0) {
    echo "上传失败:".$_FILES["file"]["error"];
} else {
    echo "上传成功!";
    move_uploaded_file($_FILES["file"]["tmp_name"], "/path/to/save/" . $_FILES["file"]["name"]);
}
?>

这个 PHP 脚本可以接收上传的文件,并将其保存到服务器上指定的目录中。

您好,上传文件到服务器需要经过以下步骤:

  1. 在客户端编写上传文件的代码(Android平台)。
  2. 在服务端编写接收文件的代码(PHP)。
  3. 使用HTTP请求将文件上传到服务器。

以下是代码示例:

廊坊阿里云代理商:android php 上传文件到服务器

Android端上传文件:

private void uploadFile() {
    OkHttpClient client = new OkHttpClient();
    String url = "http://server.com/upload.php";
    File file = new File("/sdcard/myfile.png");

    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                Log.d(TAG, "file uploaded successfully");
            }
        }
    });
}

其中,URL是服务端的接口地址,file是待上传的文件,通过RequestBody构建请求体,使用OkHttp发起POST请求。

PHP端接收文件:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

if(isset($_POST["submit"])) {
    if(getimagesize($_FILES["file"]["tmp_name"]) !== false) {
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file ". htmlspecialchars( basename( $_FILES["file"]["name"])). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

其中,$target_dir是目标文件夹,$target_file是待上传文件路径,使用$_FILES全局变量获取上传文件,使用move_uploaded_file函数将文件从临时位置移动到目标文件夹。

发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/159081.html

(0)
luotuoemo的头像luotuoemo
上一篇 2024年3月10日 11:51
下一篇 2024年3月10日 12:24

相关推荐

  • 柳州阿里云代理商:asp.net日期

    在 ASP.NET 中获取日期的方法有多种,主要包括以下几种: 使用 DateTime.Now 属性获取当前日期和时间: DateTime now = DateTime.Now; 使用 DateTime.Today 属性获取当前日期: DateTime today = DateTime.Today; 使用 DateTime.Parse 方法将字符串转换为日期…

    2023年12月29日
    25800
  • 莱州阿里云企业邮箱代理商:阿里邮箱写邮件怎么写

    莱州阿里云企业邮箱代理商:阿里邮箱的优势与好用之处 在现代社会,电子邮件已经成为人们日常工作和生活中不可或缺的重要工具。而作为一款专注于企业级用户的邮箱服务,阿里云企业邮箱在功能和安全性上都有着明显优势,让用户能够更加高效地进行邮件沟通和管理。 简洁易用的界面 阿里云企业邮箱的界面设计简洁明了,操作流畅,用户可以快速找到需要的功能。无论是撰写邮件、查看已发的…

    2024年2月26日
    25000
  • 香港阿里云代理商:as400服务器配置

    AS400服务器是一种主机服务器,提供了多种功能,包括数据存储、计算、应用程序运行等。在配置AS400服务器时,以下是一些可供参考的建议: 1.选择适当的处理器:AS400服务器通常使用IBM Power处理器,建议选择处理速度最高的处理器。 2.确定存储容量:存储容量是AS400服务器的一个重要因素。您应该根据您的数据需求选择存储容量。 3.选择网络接口卡…

    2024年3月9日
    28100
  • 包头阿里云企业邮箱代理商:阿里云旗舰级代理

    包头阿里云企业邮箱代理商:阿里云旗舰级代理 阿里云企业邮箱优势 阿里云企业邮箱是一款基于云技术的企业邮箱服务,具有以下优势: 稳定可靠:基于阿里云强大的云计算基础设施,保证邮箱系统的稳定性和可靠性。 安全性高:采用多层次的安全防护机制,保障企业邮箱数据的安全。 灵活扩展:支持根据企业需求灵活扩展邮箱容量,满足不同规模企业的需求。 移动办公:支持多端同步,随时…

    2024年2月18日
    25300
  • 扬州阿里云代理商:App列表

    阿里云控制台:用于管理和监控云服务资源,提供云服务器、云数据库等服务。 阿里云移动推送:用于推送通知消息给移动设备用户。 阿里云移动分析:用于分析移动应用的用户行为和性能数据。 阿里云CDN:用于加速静态资源的传输,提供全球覆盖的内容分发网络。 阿里云容器服务:用于部署和管理容器化应用的服务。 阿里云函数计算:用于构建和部署无服务器应用程序。 阿里云消息队列…

    2024年1月3日
    25700

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们

4000-747-360

在线咨询: QQ交谈

邮件:ixuntao@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
购买阿里云服务器请访问:https://www.4526.cn/