php+设置files,php-Android文件上传-$_FILES返回空

我正在尝试使用Android脚本将图像从Android App上传到服务器.

HTTP响应返回状态为OK:200,但是$_FILES [“ upfile”] [“ name”]返回空.

我已经检查了我的文件夹权限,Aready是777.

我的.java类

/********************UPLOAD DATA*************************************/

class UploadImg extends AsyncTask{

NetworkInfo net;

Messaging uActivity;

HttpURLConnection connection = null;

DataOutputStream outputStream = null;

DataInputStream inputStream = null;

String folderPath;

String arrayOfFiles[];

File root;

File allFiles;

String urlServer = "http://bmcpublicidade.com.br/chat/upload.php";

String lineEnd = "\r\n";

String twoHyphens = "--";

String boundary = "*****";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 10*1024*1024;

URL url;

ProgressDialog pDialog = new ProgressDialog(Messaging.this);

@Override

protected void onPreExecute() {

Log.d(" UploadImg","onPreRequest");

pDialog.setMessage("Uploading GPS Data. Please wait...");

pDialog.setIndeterminate(false);

pDialog.setCancelable(true);

pDialog.show();

}

@Override

protected Void doInBackground(Void... params) {

Log.d(" UploadData","doInBackground");

String fileName = ""+selectedPath;

HttpURLConnection conn = null;

DataOutputStream dos = null;

BufferedReader inStream = null;

String lineEnd = "rn";

String twoHyphens = "--";

String boundary = "*****";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 10*1024*1024;

String responseFromServer = "";

String urlString = "http://bmcpublicidade.com.br/chat/upload.php";

try

{

//------------------ CLIENT REQUEST

FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );

// open a URL connection to the Servlet

URL url = new URL(urlString);

// Open a HTTP connection to the URL

conn = (HttpURLConnection) url.openConnection();

// Allow Inputs

conn.setDoInput(true);

// Allow Outputs

conn.setDoOutput(true);

// Don't use a cached copy.

conn.setUseCaches(false);

// Use a post method.

conn.setRequestMethod("POST");

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

conn.setRequestProperty("enctype", "multipart/form-data");

conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

conn.setRequestProperty("upfile", fileName);

dos = new DataOutputStream( conn.getOutputStream() );

dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"upfile\"; filename='"+ selectedPath +"'" + lineEnd);

dos.writeBytes(lineEnd);

// create a buffer of maximum size

bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);

buffer = new byte[bufferSize];

// read file and write it into form...

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

while (bytesRead > 0)

{

dos.write(buffer, 0, bufferSize);

bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);

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

}

// send multipart form data necesssary after file data...

dos.writeBytes(lineEnd);

dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Responses from the server (code and message)

serverResponseCode = conn.getResponseCode();

String serverResponseMessage = conn.getResponseMessage();

Log.i("upfile", "HTTP Response is : "

+ serverResponseMessage + ": " + serverResponseCode);

if(serverResponseCode == 200){

runOnUiThread(new Runnable() {

public void run() {

String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"

+" http://**********/media/uploads/";

messageText.setText(msg);

Toast.makeText(Messaging.this, "File Upload Complete.",

Toast.LENGTH_SHORT).show();

}

});

}

// close streams

Log.e("Debug","gravando arquivo: " + fileName);

fileInputStream.close();

dos.flush();

dos.close();

}

catch (MalformedURLException ex)

{

Log.e("Debug", "erro: " + ex.getMessage(), ex);

}

catch (IOException ioe)

{

Log.e("Debug", "erro: " + ioe.getMessage(), ioe);

}

//------------------ read the SERVER RESPONSE

try {

inStream = new BufferedReader ( new InputStreamReader(conn.getInputStream()) );

String str;

while (( str = inStream.readLine()) != null)

{

Log.e("Debug","Servidor diz: "+str);

}

inStream.close();

}

catch (IOException ioex){

Log.e("Debug", "erro: " + ioex.getMessage(), ioex);

}

return null;

}

@Override

protected void onPostExecute(Void result) {

Log.d(" UploadMSG","onPost");

pDialog.dismiss();

messageText.setText("Uploaded");

}

}

/********************END OF UPLOAD*************************************/

这是我的php文件

// Where the file is going to be placed

$target_path = "uploads/";

/* Add the original filename to our target path.

Result is "/uploads/filename.extension" */

$target_path = $target_path . basename( $_FILES['upfile']['name']);

if( $_FILES['upfile'] )

{

if(move_uploaded_file($_FILES['upfile']['tmp_name'], $target_path)) {

// $qry = "UPDATE users set image=".$target_path." where username='$username'";

// $db->query($qry);

echo "O arquivo ". basename( $_FILES['upfile']['name']).

" está sendo enviado";

} else{

echo "Ocorreu um erro ao realizar envio de arquivo, por favor tente novamente!\n";

echo "Nome do arquivo: " . basename( $_FILES['upfile']['name'])."\n";

echo "target_path: " .$target_path;

}

}else

{

echo "Nenhum arquivo careregado!";

/*** ever enters here!!! ***/

}

你能帮助我吗?

谢谢 !!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
$_FILES是一个PHP超全局变量,用于在上传文件时获取上传的文件信息。$_FILES数组的用法是通过HTML表单中的<input type="file">将文件上传到web服务器,然后通过PHP脚本使用$_FILES数组来处理上传的文件。 关于多文件上传,可以通过在HTML表单中添加多个<input type="file">元素来实现。在PHP脚本中,$_FILES数组会自动处理多个上传文件。在处理多个上传文件时,$_FILES数组中的每个文件都有自己的键名。例如,如果有两个上传文件,其键名分别为file1和file2,则可以使用以下代码访问它们: ``` $file1 = $_FILES["file1"]; $file2 = $_FILES["file2"]; ``` 值得注意的是,$_FILES数组中的每个上传文件都有自己的属性。常见的属性包括:name、type、size、tmp_name和error。其中,name属性表示文件的原始名称,type属性表示文件的MIME类型,size属性表示文件的大小(以字节为单位),tmp_name属性表示文件在web服务器上的临时存储位置,error属性表示上传过程中是否出错。 在PHP脚本中,可以使用move_uploaded_file()函数将上传的文件从临时位置移动到指定的位置。例如,以下代码将上传的文件从临时位置移动到web服务器上的/uploads目录中: ``` $target_dir = "/uploads/"; $target_file = $target_dir . basename($_FILES["file"]["name"]); if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) { echo "文件上传成功"; } else { echo "文件上传失败"; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值