Datei nicht gefunden Ausnahme beim Versuch, eine Datei von einer Android-Anwendung auf einen xampp-Server hochzuladen
In meiner Android-Anwendung versuche ich, eine Datei anzuhängen, indem ich den Speicher meines Telefons durchsuche, und dann versuche ich, sie auf den Server hochzuladen. Ich kann nach Dateien suchen und sie anhängen, während ich sie auf den Server hochlade. Ich erhalte die Ausnahme "Datei nicht gefunden". Bitte helfen Sie mir, dieses Problem zu lösen. Lassen Sie mich wissen, was ich vermisse. Wenn es einen besseren Weg gibt, lass es mich bitte wissen.
FileUtils.java:
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import java.net.URISyntaxException;
/**
* Created by iFocus on 6/16/2015.
*/
public class FileUtils {
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
}
Search, Attach und uploadtoServer-Methoden:
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
Toast.makeText(getActivity(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d("iFocus", "The value of data is " + data);
Log.d("TAG", "File Uri: " + uri.toString());
fileName = uri.toString();
selectedFileName.setText(uri.toString());
// Get the path
String path = null;
try {
path = FileUtils.getPath(getActivity(), uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Log.d("TAG", "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
InputStreamReader inStream = null;
String existingFileName = fileName;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
String urlString = "http://192.168.1.21/uploadToServer.php";
try {
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
// 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("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + 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);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line);
}
String str ;
str = sb.toString();
Log.d("iFocus", "The value of str is " +str);
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
Meine Adb Logcat-Ablaufverfolgung:
06-17 10:43:21.484 16788-16788/com.blo.ifo.ifocusblogs E/Debug﹕ error: content:/com.android.providers.downloads.documents/document/1541: open failed: ENOENT (No such file or directory)
java.io.FileNotFoundException: content:/com.android.providers.downloads.documents/document/1541: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:456)
at java.io.FileInputStream.<init>(FileInputStream.java:76)
at com.blo.ifo.ifocusblogs.InsertAndroidPost.doFileUpload(InsertAndroidPost.java:267)
at com.blo.ifo.ifocusblogs.InsertAndroidPost.access$400(InsertAndroidPost.java:50)
at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:539)
at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:445)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Posix.open(Native Method)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
at libcore.io.IoBridge.open(IoBridge.java:442)
at java.io.FileInputStream.<init>(FileInputStream.java:76)
at com.blo.ifo.ifocusblogs.InsertAndroidPost.doFileUpload(InsertAndroidPost.java:267)
at com.blo.ifo.ifocusblogs.InsertAndroidPost.access$400(InsertAndroidPost.java:50)
at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:539)
at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:445)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
06-17 10:43:21.484 16788-16788/com.blo.ifo.ifocusblogs D/AndroidRuntime﹕ Shutting down VM
06-17 10:43:21.487 16788-16788/com.blo.ifo.ifocusblogs E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.blo.ifo.ifocusblogs, PID: 16788
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.InputStream java.net.HttpURLConnection.getInputStream()' on a null object reference
at com.blo.ifo.ifocusblogs.InsertAndroidPost.doFileUpload(InsertAndroidPost.java:322)
at com.blo.ifo.ifocusblogs.InsertAndroidPost.access$400(InsertAndroidPost.java:50)
at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:539)
at com.blo.ifo.ifocusblogs.InsertAndroidPost$InsertServerAndroidAdminPost.onPostExecute(InsertAndroidPost.java:445)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Mein PHP-Skript:
<?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['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
Ich kann den ausgewählten Dateinamen und den Namen, den ich an die Upload-Datei übergebe, abrufen. Ich habe alle erforderlichen Berechtigungen in Manifest. Bitte lassen Sie mich meinen Fehler wissen. Alle Vorschläge sind willkommen. Bitte lassen Sie mich wissen, wenn weitere Details erforderlich sind. Danke im Voraus