Файл Android не загружается на сервер

Я создаю папку, в которой я создаю текстовый файл и сохраняю их в каталоге кэша, используя эту функцию:

public void GenerateFile(String sFileName, String sBody){
try
{
String foldername="TestFolder";
File root = new File(context.getCacheDir() + "/"+foldername);
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.d("Exception is",e.toString());
}
}

Затем я пытаюсь опубликовать этот файл на сервере, это моя деятельность:

 GenerateFile("ConfigFile.txt","test\ndfssdfdsf\ndfsdsdfsfds\nsdfdfs");

uploadFilePath=this.getCacheDir() + "/TestFolder/ConfigFile.txt";
upLoadServerUri = "http://www.*****.com/test/uploadtoserver.php";

uploadButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{

dialog = ProgressDialog.show(PostFile.this, "", "Uploading file...", true);

new Thread(new Runnable()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
messageText.setText("uploading started.....");
}
});

uploadFile(uploadFilePath);

}
}).start();
}
});
}

public int uploadFile(String sourceFileUri)
{


String fileName = sourceFileUri;

HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);

if (!sourceFile.isFile())
{

dialog.dismiss();

Log.e("uploadFile", "Source File not exist :"+ uploadFilePath);

runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :" + uploadFilePath);
}
});

return 0;

}
else
{
try
{

// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);

// Open a HTTP  connection to  the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
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("myFile",fileName);
Log.d("File Name is", fileName);
dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + 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("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);

if(serverResponseCode == 200)
{


InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;

while ((line = reader.readLine()) != null) {
result.append(line);
Log.d("Result is",String.valueOf(result));

}

runOnUiThread(new Runnable()
{
public void run()
{

String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"+" serverpath"+uploadFileName;

messageText.setText(msg);
Toast.makeText(PostFile.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}

//close the streams //
fileInputStream.close();
dos.flush();
dos.close();

}
catch (MalformedURLException ex)
{

dialog.dismiss();
ex.printStackTrace();

runOnUiThread(new Runnable()
{
public void run()
{
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(PostFile.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});

Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
}
catch (Exception e)
{

dialog.dismiss();
e.printStackTrace();

runOnUiThread(new Runnable()
{
public void run()
{
messageText.setText("Got Exception : see logcat ");
Toast.makeText(PostFile.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload Exception", "Exception : "+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;

Это код php:

    <?php

if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "error";
}
else{
$filename = $_FILES['myFile']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);

echo "success -- extension: ." . $ext;
}
}
else{
echo "no file found";
}

?>

Файл не загружается, страница php возвращает файл не найден, любая помощь?

2

Решение

Вы проверили, что пользователь apache (или какой бы пользователь php ни работал под именем) имеет права на запись в каталог, указанный в $ file_path?

Поместите следующий код в ту же директорию, где находится ваш PHP-скрипт, а затем перейдите к нему в веб-браузере.

<?php

$file_path = 'uploads/';

$success = file_put_contents($file_path . "afile", "This is a test");

if($success === false) {
echo "Couldn't write file";
} else {
echo "Wrote $success bytes";
}

?>

Дает ли это сообщение об успехе или сообщение об ошибке?

Если выдается сообщение об ошибке, попробуйте изменить владельца каталога загрузок.

0

Другие решения

Попробуй это.
Я проверил этот код, он отлично работает для загрузки изображений

// Get image string posted from Android App
$base = $_POST["image"];
// Get file name posted from Android App
$filename = $_POST["filename"];
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// Images will be saved under 'www/imgupload/uplodedimages' folder
$file = fopen($filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete, Please check your php file directory';
0