android接收文件上传,Android上传文件到Web服务器,PHP接收文件

这个博客展示了如何在Android应用中使用HttpURLConnection实现文件上传到PHP服务器的过程,包括设置请求头、分块上传及进度更新。通过AsyncTask进行异步处理,确保用户体验流畅。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.tianlei.httpUrlConnection_PHPUpload;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import android.app.ProgressDialog;

import android.content.Context;

import android.os.AsyncTask;

public class Upload{

/** Called when the activity is first created. */

/**

* Upload file to web server with progress status, client: android;

* server:php

* **/

private String urlServer = "http://120.126.16.52/uploadfile.php";  //the server address to process the uploaded file

public String filepath;   //the file path to upload

private Context c;

public Upload(Context c, String filepath){

this.c = c;

this.filepath = filepath;

}

//开始下载并显示进度条

public void startUpload(){

FileUploadTask fileUploadTask = new FileUploadTask();

fileUploadTask.execute();

}

// show Dialog method

/*private void showDialog(String mess) {

new AlertDialog.Builder(c).setTitle("Message")

.setMessage(mess)

.setNegativeButton("确定", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

}

}).show();

}*/

class FileUploadTask extends AsyncTask {

private ProgressDialog dialog = null;

HttpURLConnection connection = null;

DataOutputStream outputStream = null;

DataInputStream inputStream = null;

String lineEnd = "\r\n";

String twoHyphens = "--";

String boundary = "*****";

File uploadFile = new File(filepath);

long totalSize = uploadFile.length(); // Get size of file, bytes

/*该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作,

* 如在界面上显示一个进度条。 */

@Override

protected void onPreExecute() {

dialog = new ProgressDialog(c);

dialog.setMessage("正在上传...");

dialog.setIndeterminate(false);

dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

dialog.setProgress(0);

dialog.show();

}

/*将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行

* 那些很耗时的后台计算工作。可以调用 publishProgress方法来更新实时的任务进度。

* 该方法是抽象方法,子类必须实现。*/

@Override

protected Void doInBackground(Object... arg0) {

long length = 0;

int progress;

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 256 * 1024;// 256KB

try {

FileInputStream fileInputStream = new FileInputStream(new File(

filepath));

URL url = new URL(urlServer);

connection = (HttpURLConnection) url.openConnection();

// Set size of every block for post

connection.setChunkedStreamingMode(256 * 1024);// 256KB

// Allow Inputs & Outputs

connection.setDoInput(true);

connection.setDoOutput(true);

connection.setUseCaches(false);

// Enable POST method

connection.setRequestMethod("POST");

connection.setRequestProperty("Connection", "Keep-Alive");

connection.setRequestProperty("Charset", "UTF-8");

connection.setRequestProperty("Content-Type",

"multipart/form-data;boundary=" + boundary);

outputStream = new DataOutputStream(

connection.getOutputStream());

outputStream.writeBytes(twoHyphens + boundary + lineEnd);

outputStream

.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""

+ filepath + "\"" + lineEnd);

outputStream.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);

buffer = new byte[bufferSize];

// Read file

bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {

outputStream.write(buffer, 0, bufferSize);

length += bufferSize;

progress = (int) ((length * 100) / totalSize);

//调用 publishProgress方法来更新实时的任务进度

publishProgress(progress);

bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);

bytesRead = fileInputStream.read(buffer, 0, bufferSize);

}

outputStream.writeBytes(lineEnd);

outputStream.writeBytes(twoHyphens + boundary + twoHyphens

+ lineEnd);

//进度条100,下载完成

publishProgress(100);

/*通过使用Dialog()对话框显示进度条*/

// Responses from the server (code and message)

//int serverResponseCode = connection.getResponseCode();

//String serverResponseMessage = connection.getResponseMessage();

/* 将Response显示于Dialog */

// Toast toast = Toast.makeText(UploadtestActivity.this, ""

// + serverResponseMessage.toString().trim(),

// Toast.LENGTH_LONG);

// showDialog(serverResponseMessage.toString().trim());

/* 取得Response内容 */

// InputStream is = connection.getInputStream();

// int ch;

// StringBuffer sbf = new StringBuffer();

// while ((ch = is.read()) != -1) {

// sbf.append((char) ch);

// }

//

// showDialog(sbf.toString().trim());

fileInputStream.close();

outputStream.flush();

outputStream.close();

} catch (Exception ex) {

// Exception handling

// showDialog("" + ex);

// Toast toast = Toast.makeText(UploadtestActivity.this, "" +

// ex,

// Toast.LENGTH_LONG);

}

return null;

}

/*在publishProgress方法被调用后,UI thread将调用这个方法从而在界面上展示任务

*的进展情况,例如通过一个进度条进行展示。*/

@Override

protected void onProgressUpdate(Integer... progress) {

dialog.setProgress(progress[0]);

}

/*在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,

*后台的计算结果将通过该方法传递到UI thread.*/

@Override

protected void onPostExecute(Void result) {

try {

dialog.dismiss();  //dismiss the dialog

// TODO Auto-generated method stub

} catch (Exception e) {

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值