0
我不是PHP專家,因此我從互聯網和本頁面的問題中瞭解了很多東西。我需要發送一個文件到WAMP服務器(唱歌的PHP腳本),併發送一個字符串以創建目標路徑,這取決於日期和發送的字符串。 目前,目標路徑僅基於實際日期。例如2013-09-27,但我希望成爲2013-09-27-XX,其中XX是設備發送到服務器以及上傳文件的字符串。Android:上傳文件並使用JSON/PHP發送字符串
這裏是我用來上傳文件到服務器的代碼。
public void upload() throws Exception {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = "/sdcard/"+Ident.getDNI()+"_"+Nombres.getNom()+"_"+Nombres.getApe1()+"_"+Nombres.getApe2()+".xml";
String urlServer = "http://10.0.0.15/subida/upload_file.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
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=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
String serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
這裏是PHP腳本我用得到的文件(根據日期):我想我應該在這裏添加類似$SentString = $_POST('sentstring)
,然後將其添加到目標路徑
<?php
mkdir($target_path.date("Y-m-d"));
$target_path = $target_path .date("Y-m-d") ."/" .basename($_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "El fichero ". basename($_FILES['uploadedfile']['name'])." ha sido enviado";
} else{
echo "Hubo un error, inténtalo de nuevo!";
}
?>
:
$target_path = $target_path .date("Y-m-d")-$SentString ."/" .basename($_FILES['uploadedfile']['name']);
但是,我應該添加到Android客戶端部分?
謝謝您的時間
你好感謝你的幫助,但是還有一種方法仍在使用我目前使用的代碼? – Katherine99
實際上這個庫很容易從客戶端使用,數據也很容易從服務器端解析。正如你在實體中看到的那樣,我們也可以發送字符串值對。所以根據我。代碼不會超過5分鐘。 –