【发布时间】:2014-08-19 13:49:29
【问题描述】:
我正在尝试使用应用程序将文件从手机上传到我的电脑。我的电脑中有 Android 应用程序和一个带有 PHP 脚本的网络服务器。当我尝试上传文件时,PHP 脚本Undefined index: uploadedfile in .... on line 3 和Undefined index: uploadedfile in .... on line 4 出现以下错误。我不知道问题出在哪里以及为什么会发生。我的 Android 代码如下:
public class Upload {
URL connectURL;
String responseString;
String fileName;
byte[] dataToServer;
Upload(String urlString, String fileName ){
try{
connectURL = new URL(urlString);
}catch(Exception ex){
Log.i("URL FORMATION","MALFORMATED URL");
}
this.fileName = fileName;
}
void doStart(FileInputStream stream){
fileInputStream = stream;
thirdTry();
}
FileInputStream fileInputStream = null;
void thirdTry() {
String existingFileName = fileName;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="3rd";
try{
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"archivo[]\";filename=\"" + existingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int 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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
InputStream is = conn.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){
b.append( (char)ch );
}
String s=b.toString();
Log.e("Response",s);
dos.close();
}
catch (MalformedURLException ex){
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe){
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
}
还有我的 PHP 代码:
$target_path = "uploads/";
$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!";
}
【问题讨论】:
标签: php android file-upload