Java 使用Android将文件上载到PHP脚本
我想上传一个文件到PHP脚本。上传似乎工作正常,它正在发送数据。但是每次PHP脚本都告诉我,$\u文件是空的。。。我不知道我做错了什么。。知道我的代码有什么问题吗Java 使用Android将文件上载到PHP脚本,java,android,Java,Android,我想上传一个文件到PHP脚本。上传似乎工作正常,它正在发送数据。但是每次PHP脚本都告诉我,$\u文件是空的。。。我不知道我做错了什么。。知道我的代码有什么问题吗 import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Settings.Secure;
import android.util.Log;
public class Upload extends AsyncTask<Object, Integer, String> {
URL connectURL;
String responseString;
String usernameString;
Context con;
String iFileName;
byte[] dataToServer;
FileInputStream fileInputStream = null;
void Sending() {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag = "Info";
try {
Log.e(Tag, "Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection) connectURL.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("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
Log.d("Info", iFileName);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
Log.e(Tag, "sending...");
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag, "File Sent, Response: " + String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
Log.i("Response", s);
dos.close();
String aidString = Secure.getString(con.getContentResolver(), Secure.ANDROID_ID);
//new BackgroundPost(new OnTaskComplete() {}).execute(usernameString, s, "0", "0", aidString, "");
} catch (MalformedURLException ex) {
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
public void run() {
// TODO Auto-generated method stub
}
@Override
protected String doInBackground(Object... params) {
try {
connectURL = new URL(conf.d + "upload.php");
usernameString = String.valueOf(params[0]);
con = (Context)params[1];
Random random = new Random();
String u = (String) params[2];
Log.d("Info","u: " + u);
iFileName = random.nextInt() + "." + u.substring(u.lastIndexOf(".")+1);
Log.d("Info","filename: " + iFileName);
fileInputStream = new FileInputStream(u);
Sending();
} catch (Exception ex) {
ex.printStackTrace();
Log.i("HttpFileUpload", "URL Malformatted");
}
// TODO Auto-generated method stub
return null;
}
}
import java.io.DataOutputStream;
导入java.io.FileInputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.net.HttpURLConnection;
导入java.net.MalformedURLException;
导入java.net.URL;
导入java.util.Random;
导入android.content.Context;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.provider.Settings.Secure;
导入android.util.Log;
公共类上载任务{
URL-connectURL;
弦乐;
字符串usernameString;
上下文con;
字符串iFileName;
字节[]dataToServer;
FileInputStream FileInputStream=null;
无效发送(){
字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“*******”;
String Tag=“Info”;
试一试{
Log.e(标记“启动Http文件发送到URL”);
//打开到URL的HTTP连接
HttpURLConnection conn=(HttpURLConnection)connectURL.openConnection();
//允许输入
conn.setDoInput(真);
//允许输出
连接设置输出(真);
//不要使用缓存副本。
conn.SETUSECHACHES(假);
//使用post方法。
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“内容类型”、“多部分/表单数据;边界=“+boundary”);
DataOutputStream dos=新的DataOutputStream(conn.getOutputStream());
Log.d(“信息”,iFileName);
writeBytes(“内容处理:表单数据;名称=\”uploadedfile\“文件名=\”+iFileName+“\”+lineEnd);
dos.writeBytes(lineEnd);
Log.e(标记“写入标题”);
//创建最大大小的缓冲区
int bytesavable=fileInputStream.available();
int maxBufferSize=1024;
int bufferSize=Math.min(字节可用,maxBufferSize);
字节[]缓冲区=新字节[bufferSize];
//读取文件并将其写入表单。。。
int bytesRead=fileInputStream.read(buffer,0,bufferSize);
而(字节读取>0){
Log.e(标记“发送…”);
写入(缓冲区,0,缓冲区大小);
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
}
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+两个连字符+行结束);
//合流
fileInputStream.close();
dos.flush();
Log.e(标记“文件已发送,响应:”+String.valueOf(conn.getResponseCode()));
InputStream is=conn.getInputStream();
//从服务器检索响应
int-ch;
StringBuffer b=新的StringBuffer();
而((ch=is.read())!=-1){
b、 追加((char)ch);
}
字符串s=b.toString();
Log.i(“响应”,s);
dos.close();
String aidString=Secure.getString(con.getContentResolver(),Secure.ANDROID_ID);
//新建BackgroundPost(new OnTaskComplete(){}).execute(usernameString,s,“0”,“0”,aidString,”);
}捕获(格式错误){
Log.e(标记,“URL错误:+ex.getMessage(),ex);
}
捕获(ioe异常ioe){
Log.e(标记“IO错误:”+ioe.getMessage(),ioe);
}
}
公开募捐{
//TODO自动生成的方法存根
}
@凌驾
受保护的字符串doInBackground(对象…参数){
试一试{
connectURL=新URL(conf.d+“upload.php”);
usernameString=String.valueOf(参数[0]);
con=(上下文)参数[1];
随机=新随机();
字符串u=(字符串)参数[2];
日志d(“信息”,“u:+u”);
iFileName=random.nextInt()+“”+u.substring(u.lastIndexOf(“.”+1);
Log.d(“信息”,“文件名:”+iFileName);
fileInputStream=新的fileInputStream(u);
发送();
}捕获(例外情况除外){
例如printStackTrace();
Log.i(“HttpFileUpload”,“URL格式错误”);
}
//TODO自动生成的方法存根
返回null;
}
}
以及PHP文件:
<?php
$target_path = "uploads/";
print_r($_FILES);
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file " . basename($_FILES['uploadedfile']['name']) . " has been uploaded";
}
else {
echo "There was an error uploading the file, please try again!";
}
?>
我认为您错过了在fileInputStream.close()之后关闭边界块
我建议您使用apache commons上传文件。