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

Android - unregisterReceiver concept in detail?
Google Play Store warning about fewer devices supported by updated APK
Differences between Push functions in RIM OS (BIS), IOS and android
How to show the lockscreen after tapping a button and closing the activity?
Some code in Android APIDemos Sensors.java puzzle me
Android JNI APK Packing
Android/Mobile Webkit CSS Background-Attachment:Fixed Not Working?
How can I make sure Android Beam doesn't start a new instance of my 'singleTop' activity?
Android Unable to resolve host
couldn't find import for class android.database.Cursor in AIDL file
Putting settings menu to Home Widget
Android Emulator Contacts Manager source code?
Newbie: Use Android intents privately?
get currently displayed fragment
android to receive a string from java server after successful connection and sending of message
Android App/AVD problems

Categories

HOME
django
embedded
httparty
search
string
codenvy
sitecore
nuget
zip
android-json
opengl-3
performancepoint
project
vimdiff
why3
supervisor
flatpak
mvc-mini-profiler
vuejs
video-editing
asciidoctor-pdf
jquery-ias
object-storage
game-theory
shared
fractions
linked-data
kudu
playstation-portable
sammy.js
html-encode
reverse
pdw-file-browser
processwire
getlasterror
engine.io
searchkit
imagenet
google-earth-engine
dm-script
metaprogramming
p4merge
hackintosh
attributeerror
android-ibeacon
subclipse
chronicle-map
tcc
procfile
double-click
proget
openrasta
jquery-ui-draggable
dotnet-httpclient
hammer.js
dbcontext
tf
flac
pybrain
structuremap4
cvxpy
ziparchive
i386
stream-processing
aurora
beanstalk
httpruntime.cache
roadkill-wiki
xvim
intel-c++
visual-sourcesafe-2005
jdk1.7
baasbox
aspectj-maven-plugin
broadband
java-security
variadic-templates
execve
webmatrix-3
big-ip
structuremap3
spy++
parallel-testing
live555
jjaql
ebay-lms
cocoalibspotify-2.0
rolify
mvc-editor-templates
cmmi
http-status-code-410
device-width
oracle-enterprise-linux
jsr286
google-maps-mobile
google-ajax-api
uideviceorientation
rowlex
binomial-heap
interop-domino
linfu-dynamicproxy
unmanagedresources
ifilter
blind

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