Не загружается файл на сервер Android
Сделал подключение к серверу, все запросы идут на Ура, какое-то время изображения грузились на сервер потом перестали. Ошибок никаких нет. При загрузке пишет что файл успешно обновлен, сервер работает без проблем, вылетала ошибка по типу что нету доступа к файлу на телефоне, хотя изображение спокойно грузилось в ImageView решил проблему
android:requestLegacyExternalStorage="true"
проблема с доступом записи решилась, но файл все равно не грузится. Добавил разрешение на запись файлов
через sudo chmod -R 777 , тоже не помогло
Класс с загрузкой файла
public class UploadFiles {
private String sourceFileUri = "";
private String nameFile = "";
public UploadFiles(final String sourceFileUri, final String nameFile){
this.sourceFileUri = sourceFileUri;
this.nameFile = nameFile;
new UploadFileAsync().execute("");
}
private class UploadFileAsync extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
uploadFile(sourceFileUri, nameFile);
return "Executed";
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
public void uploadFile(String sourceFileUri, String fileName) {
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()) {
Log.e("uploadFile", "Source File not exist :"+sourceFileUri);
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("http://ип сервера/gpstracker/api/v1/users/uploadfile.php");
// 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("uploaded_file", 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)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
} // End else block
}
}
}
Вызываю класс следующим образом
new UploadFiles(picturePath, filename);
если добавить картинку с соответствующим uri в ImageView, она отображаться, это значит что путь к картинке правильный
php файл на сервере
<?php
$file_path = "var/www/html/gpstracker/api/v1/users/images/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{ echo "fail";}
?>
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gpstracker.anton">
<application
android:requestLegacyExternalStorage="true"
android:allowBackup="true"
android:networkSecurityConfig="@xml/network_security_config"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
<uses-library android:name="org.apache.http.legacy" android:required="false" />
<activity android:name=".Pages.Login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Pages.Registration">
</activity>
<activity android:name=".Pages.Rooms">
</activity>
<activity android:name=".Pages.MapsActivity">
</activity>
<meta-data
android:name="com.google.android.actions"
android:resource="@xml/network_security_config" />
<meta-data
android:name="com.google.android.gms.ads.AD_MANAGER_APP"
android:value="true" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="xxxxxxxxxxxxxxxxxxxxxxxx"/>
</application>
<uses-permission android:name="com.gpstracker.anton.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.example.googlemaps.permission.MAPS_RECEIVE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<permission
android:name="com.example.googlemaps.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
</manifest>
Debug
V/FA: Recording user engagement, ms: 4532
V/FA: Activity paused, time: 2079317988
D/FA: Application going to the background
V/FA: Activity resumed, time: 2079321093
I/AdrenoGLES: QUALCOMM build : f2ab992, I401605978b
Build Date : 09/28/19
OpenGL ES Shader Compiler Version: EV031.27.05.01
Local Branch :
Remote Branch :
Remote Branch :
Reconstruct Branch :
Build Config : S L 8.0.11 AArch64
I/AdrenoGLES: PFP: 0x005ff112, ME: 0x005ff066
W/pstracker.anto: Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setUseSessionTickets(Z)V (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setHostname(Ljava/lang/String;)V (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->getAlpnSelectedProtocol()[B (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setAlpnProtocols([B)V (greylist,core-platform-api, reflection, allowed)
W/pstracker.anto: Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (greylist,core-platform-api, reflection, allowed)
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
I/System.out: New record created successfully
I/DpmTcmClient: RegisterTcmMonitor from: $Proxy0
I/Choreographer: Skipped 71 frames! The application may be doing too much work on its main thread.
I/OpenGLRenderer: Davey! duration=1186ms; Flags=0, IntendedVsync=977843732379322, Vsync=977844915712608, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=977844916192021, AnimationStart=977844916238011, PerformTraversalsStart=977844916460251, DrawStart=977844916782438, SyncQueued=977844917081396, SyncStart=977844917343063, IssueDrawCommandsStart=977844917414782, SwapBuffers=977844918481396, FrameCompleted=977844919442230, DequeueBufferDuration=138000, QueueBufferDuration=644000,
V/FA: Recording user engagement, ms: 2985
V/FA: Activity paused, time: 2079324079
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@84bec54
V/FA: onActivityCreated
V/FA: Activity resumed, time: 2079324151
W/System: A resource failed to call close.
I/Choreographer: Skipped 42 frames! The application may be doing too much work on its main thread.
I/OpenGLRenderer: Davey! duration=727ms; Flags=0, IntendedVsync=977845015754233, Vsync=977845715754205, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=977845716684886, AnimationStart=977845716736657, PerformTraversalsStart=977845717501188, DrawStart=977845731924000, SyncQueued=977845736767542, SyncStart=977845737228636, IssueDrawCommandsStart=977845737399052, SwapBuffers=977845740745042, FrameCompleted=977845743301136, DequeueBufferDuration=137000, QueueBufferDuration=1966000,
I/OpenGLRenderer: Davey! duration=725ms; Flags=0, IntendedVsync=977845015754233, Vsync=977845715754205, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=977845716684886, AnimationStart=977845716736657, PerformTraversalsStart=977845717501188, DrawStart=977845737657282, SyncQueued=977845737685980, SyncStart=977845743715667, IssueDrawCommandsStart=977845743802230, SwapBuffers=977845746211344, FrameCompleted=977845747498740, DequeueBufferDuration=297000, QueueBufferDuration=441000,
I/uploadFile: HTTP Response is : OK: 200
I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread.
V/FA: Inactivity, disconnecting from the service
Другие запросы на получение json записей или добавление пользователей в БД проходят успешно
UPD: Не понятно как. Но было так что я в очередной раз сделал запрос и оно загрузило сразу несколько картинок, старые которые я раньше по запросу отправял. Не знаю в чем дело. Может в сервере?