android


How to get file path , When uploading a file to server?


I am developing a simple application in which user can upload his document to server. I am able to upload file to server but the problem i am getting is , when i am selecting file from this location /storage/sdcard/sample.txt ,i am able to upload but when i am selecting the file from different location the file is not uploading and in logcat i am getting this location /storage/sdcard/demo.docx, "demo.docx" is file which i selected from different location
MyLogcat
04-20 18:31:45.990 1404-2066/? W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
04-20 18:31:45.995 1404-1432/? W/IntentResolver: resolveIntent: multiple matches, only some with CATEGORY_DEFAULT
04-20 18:31:45.995 1404-1432/? I/ActivityManager: START u0 {act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=*/* cmp=com.android.documentsui/.DocumentsActivity} from uid 10217 on display 0
04-20 18:31:45.997 1404-1432/? V/WindowManager: addAppToken: AppWindowToken{12932f9c token=Token{1cf9a30f ActivityRecord{1b7ac06e u0 com.android.documentsui/.DocumentsActivity t2252}}} to stack=1 task=2252 at 1
04-20 18:31:46.081 1404-4882/? V/WindowManager: Adding window Window{1596757a u0 com.android.documentsui/com.android.documentsui.DocumentsActivity} at 3 of 6 (after Window{e2669c0 u0 org.pitechnologies.pi_technologies1/org.pitechnologies.pi_technologies1.FilePik})
04-20 18:31:46.124 2844-2862/? W/EGL_emulation: eglSurfaceAttrib not implemented
04-20 18:31:46.125 2844-2862/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5e0b5a0, error=EGL_SUCCESS
04-20 18:31:46.202 1404-1431/? W/IntentResolver: resolveIntent: multiple matches, only some with CATEGORY_DEFAULT
04-20 18:31:46.210 1404-1559/? I/ActivityManager: Displayed com.android.documentsui/.DocumentsActivity: +185ms
04-20 18:31:46.240 5054-5069/? D/OpenGLRenderer: endAllStagingAnimators on 0xb41c6b80 (RippleDrawable) with handle 0xb43da890
04-20 18:31:46.259 2844-2844/? W/ResourceType: No package identifier when getting value for resource number 0x00000000
04-20 18:31:46.259 2844-2844/? W/PackageManager: Failure retrieving resources for com.android.music: Resource ID #0x0
04-20 18:31:46.285 2844-2844/? D/Documents: Current stack:
04-20 18:31:46.285 2844-2844/? D/Documents: * Root{authority=com.android.providers.downloads.documents, rootId=downloads, title=Downloads}
04-20 18:31:46.285 2844-2844/? D/Documents: +-- Document{docId=downloads, name=null}
04-20 18:31:46.292 2844-4869/? D/Documents: userMode=0, userSortOrder=0 --> mode=1, sortOrder=2
04-20 18:31:46.300 2844-2844/? W/ResourceType: No package identifier when getting value for resource number 0x00000000
04-20 18:31:46.300 2844-2844/? W/PackageManager: Failure retrieving resources for com.android.music: Resource ID #0x0
04-20 18:31:46.336 2844-4869/? W/Documents: Failed to load thumbnail for content://com.android.providers.downloads.documents/document/2: java.io.FileNotFoundException: No such file or directory
04-20 18:31:48.897 1404-2066/? W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
04-20 18:31:48.908 2844-2844/? D/Documents: onFinished() [content://com.android.providers.downloads.documents/document/4]
04-20 18:31:48.939 5054-5054/? I/tagconvertstr-->: [demo.docx]
04-20 18:31:48.963 5054-5069/? W/EGL_emulation: eglSurfaceAttrib not implemented
04-20 18:31:48.963 5054-5069/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa50e52e0, error=EGL_SUCCESS
04-20 18:31:49.390 2844-2844/? I/art: Explicit concurrent mark sweep GC freed 3193(245KB) AllocSpace objects, 2(40KB) LOS objects, 30% free, 1142KB/1654KB, paused 9.317ms total 17.764ms
04-20 18:31:49.470 2844-2844/? I/art: Explicit concurrent mark sweep GC freed 595(68KB) AllocSpace objects, 2(40KB) LOS objects, 33% free, 1033KB/1545KB, paused 1.860ms total 24.646ms
04-20 18:31:49.490 2844-2844/? I/art: Explicit concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 33% free, 1033KB/1545KB, paused 1.842ms total 19.211ms
04-20 18:31:49.493 2844-2844/? E/StrictMode: class com.android.documentsui.DocumentsActivity; instances=2; limit=1
android.os.StrictMode$InstanceCountViolation: class com.android.documentsui.DocumentsActivity; instances=2; limit=1
at android.os.StrictMode.setClassInstanceLimit(StrictMode.java:1)
04-20 18:31:49.984 2094-2108/? I/art: Background sticky concurrent mark sweep GC freed 32252(1965KB) AllocSpace objects, 0(0B) LOS objects, 21% free, 7MB/9MB, paused 10.375ms total 29.108ms
04-20 18:31:50.787 1404-2066/? W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
04-20 18:31:50.806 5054-5089/? W/System.err: java.io.FileNotFoundException: /storage/sdcard/demo.docx: open failed: ENOENT (No such file or directory)
04-20 18:31:50.806 5054-5089/? W/System.err: at libcore.io.IoBridge.open(IoBridge.java:456)
04-20 18:31:50.806 5054-5089/? W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:76)
04-20 18:31:50.806 5054-5089/? W/System.err: at org.apache.http.entity.mime.content.FileBody.writeTo(FileBody.java:78)
04-20 18:31:50.806 5054-5089/? W/System.err: at org.apache.james.mime4j.message.MessageWriter.writeBody(MessageWriter.java:76)
04-20 18:31:50.806 5054-5089/? W/System.err: at org.apache.http.entity.mime.HttpMultipart.doWriteTo(HttpMultipart.java:202)
04-20 18:31:50.806 5054-5089/? W/System.err: at org.apache.http.entity.mime.HttpMultipart.writeTo(HttpMultipart.java:223)
04-20 18:31:50.806 5054-5089/? W/System.err: at org.apache.http.entity.mime.MultipartEntity.writeTo(MultipartEntity.java:179)
04-20 18:31:50.806 5054-5089/? W/System.err: at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:102)
04-20 18:31:50.806 5054-5089/? W/System.err: at org.apache.http.impl.AbstractHttpClientConnection.sendRequestEntity(AbstractHttpClientConnection.java:167)
04-20 18:31:50.807 5054-5089/? W/System.err: at org.apache.http.impl.conn.AbstractClientConnAdapter.sendRequestEntity(AbstractClientConnAdapter.java:277)
04-20 18:31:50.807 5054-5089/? W/System.err: at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:242)
04-20 18:31:50.807 5054-5089/? W/System.err: at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:124)
04-20 18:31:50.807 5054-5089/? W/System.err: at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:433)
04-20 18:31:50.807 5054-5089/? W/System.err: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
04-20 18:31:50.807 5054-5089/? W/System.err: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
04-20 18:31:50.807 5054-5089/? W/System.err: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
04-20 18:31:50.807 5054-5089/? W/System.err: at org.pitechnologies.pi_technologies1.FilePik$PostDataAsyncTask.doInBackground(FilePik.java:128)
04-20 18:31:50.807 5054-5089/? W/System.err: at org.pitechnologies.pi_technologies1.FilePik$PostDataAsyncTask.doInBackground(FilePik.java:107)
04-20 18:31:50.807 5054-5089/? W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
04-20 18:31:50.807 5054-5089/? W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-20 18:31:50.807 5054-5089/? W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-20 18:31:50.807 5054-5089/? W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-20 18:31:50.807 5054-5089/? W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-20 18:31:50.807 5054-5089/? W/System.err: at java.lang.Thread.run(Thread.java:818)
04-20 18:31:50.807 5054-5089/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
04-20 18:31:50.807 5054-5089/? W/System.err: at libcore.io.Posix.open(Native Method)
04-20 18:31:50.807 5054-5089/? W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
04-20 18:31:50.808 5054-5089/? W/System.err: at libcore.io.IoBridge.open(IoBridge.java:442)
04-20 18:31:50.808 5054-5089/? W/System.err: ... 23 more
MainActivity
public class FilePik extends Activity {
Button b1,b2;
String displayName;
TextView txt_file_name_1;
private static final int PICKFILE_RESULT_CODE = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filepik);
txt_file_name_1 = (TextView)findViewById(R.id.textt);
b1 = (Button)findViewById(R.id.button12);
b2 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new PostDataAsyncTask().execute();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
}
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, PICKFILE_RESULT_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK ) {
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
displayName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.i("tagconvertstr-->", "[" + displayName + "]");
}
} finally {
cursor.close();
}
}else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
Log.i("tagconvertstr", "[" + displayName + "]");
}
txt_file_name_1.setText(displayName);
}
// txt_file_name_1.setText(displayName);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://*****/*****/newfile.php");
File file1 = Environment.getExternalStorageDirectory();
File myDir = new File(file1, displayName);
FileBody fileBody1 = new FileBody(myDir);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file1", fileBody1);
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
final String responseStr = EntityUtils.toString(resEntity)
.trim();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.e("", "RESULT : " + result);
}
}
}
You are trying to access the file in External SD card whereas it is in Internal Storage. Use the following code to get the file from Internal Storage :
String filepath="directory containing file ";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
File myInternalFile = new File(directory , filename);
You should use the file's path and not his name.Instead of
displayName = myFile.getName();
Use getPath() here:
else if (uriString.startsWith("file://")) {
displayName = myFile.getPath();
Log.i("tagconvertstr", "[" + displayName + "]");
}
You have to set specific mime Type in your case Documnent Type would work

Related Links

ping between Android devices
Does Firebase on Android keep track of users across reinstalls?
Is there a way to compile a library only for devices higher then some SDK version in Gradle in Android Studio
how to make enable touching below BottomSheet without dissmising it?
Replacing a fragment
Android Studio Error- failed to resolve support-v4:24.0.0
Android - How to add item to bottom navigation bar
TabLayout using ViewPager show JSON data in fragments
Network interface ionic get ip of device
How to make an Activity fetch data from the server automatically in android
React Native get pressed key of exernal Keyboard
Error java.lang.NullPointerException recyclerview [duplicate]
File Appender not working properly logback-android
Storing keystore password for certificate pinning in Android
Fire location event for test purpose
How to configure Android mediaCodec to create a I frame only stream?

Categories

HOME
httparty
microsoftgraph
jmeter
case
obfuscation
sh
graphics
aws-cli
settings
x264
nuget-package
iis-6
frontend
teechart
dkim
ipmitool
qsqlquery
dynamic-sql
android-7.0-nougat
digital-signature
drive
asciidoctor-pdf
breadth-first-search
dataflow-diagram
qliksense
itunes
beautifier
interbase
ms-access-web-app
spotipy
sinch
vex
eviews
glib
gojs
classcastexception
sql-delete
lubridate
zoomify
graphhopper
sim-card
recurrent-neural-network
verifiable-c
kill
numberpicker
tasm
azure-arm
magento-1.9.3
doc
trigonometry
httr
phpdbg
fclose
bluez
context-switch
azure-cli
context-sensitive-grammar
sundials
baidu
vibrate
javafx-css
omxplayer
async.js
firebase-security
pre-build-event
google-query-language
cda
httpruntime.cache
jaunt-api
jbase
dynamics-nav-2016
.bash-profile
mod-proxy
zxspectrum
xmltype
mass-assignment
mutual-authentication
openargs
windows-embedded-standard
gd-graph
model-driven-development
preload
dopostback
redis-py
boost-msm
apache-whirr
jquery-tools
webdev.webserver
xui
diagrams
strtod
glui
interop-domino
cldc
scrubyt

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App