การขอไฟล์ที่แชร์
จัดทุกอย่างให้เป็นระเบียบอยู่เสมอด้วยคอลเล็กชัน
บันทึกและจัดหมวดหมู่เนื้อหาตามค่ากำหนดของคุณ
เมื่อแอปต้องการเข้าถึงไฟล์ที่แชร์โดยแอปอื่น แอปที่ส่งคำขอ (ไคลเอ็นต์)
มักจะส่งคำขอไปยังแอปที่แชร์ไฟล์ (เซิร์ฟเวอร์) ในกรณีส่วนใหญ่ คำขอ
เริ่มใช้ Activity
ในแอปเซิร์ฟเวอร์ที่แสดงไฟล์ที่แชร์ได้
ผู้ใช้เลือกไฟล์ หลังจากนั้นแอปเซิร์ฟเวอร์จะส่ง URI เนื้อหาของไฟล์ไปยัง
แอปไคลเอ็นต์
บทเรียนนี้แสดงวิธีที่แอปไคลเอ็นต์ร้องขอไฟล์จากแอปเซิร์ฟเวอร์และรับ
URI เนื้อหาจากแอปเซิร์ฟเวอร์ และเปิดไฟล์โดยใช้ URI เนื้อหา
ส่งคำขอไฟล์
หากต้องการขอไฟล์จากแอปเซิร์ฟเวอร์ แอปไคลเอ็นต์จะเรียก
startActivityForResult
ที่มี
Intent
ที่มีการดำเนินการ เช่น
ACTION_PICK
และประเภท MIME ที่แอปไคลเอ็นต์
สามารถจัดการได้
ตัวอย่างเช่น ข้อมูลโค้ดต่อไปนี้แสดงวิธีส่ง
Intent
ไปยังแอปของเซิร์ฟเวอร์เพื่อเริ่ม
Activity
อธิบายไว้ในการแชร์ไฟล์:
Kotlin
class MainActivity : Activity() {
private lateinit var requestFileIntent: Intent
private lateinit var inputPFD: ParcelFileDescriptor
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
requestFileIntent = Intent(Intent.ACTION_PICK).apply {
type = "image/jpg"
}
...
}
...
private fun requestFile() {
/**
* When the user requests a file, send an Intent to the
* server app.
* files.
*/
startActivityForResult(requestFileIntent, 0)
...
}
...
}
Java
public class MainActivity extends Activity {
private Intent requestFileIntent;
private ParcelFileDescriptor inputPFD;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestFileIntent = new Intent(Intent.ACTION_PICK);
requestFileIntent.setType("image/jpg");
...
}
...
protected void requestFile() {
/**
* When the user requests a file, send an Intent to the
* server app.
* files.
*/
startActivityForResult(requestFileIntent, 0);
...
}
...
}
เข้าถึงไฟล์ที่ขอ
แอปเซิร์ฟเวอร์จะส่ง URI เนื้อหาของไฟล์กลับไปยังแอปไคลเอ็นต์ใน
Intent
มีการส่ง Intent
นี้ไปยังไคลเอ็นต์
ในการลบล้าง onActivityResult()
ครั้งเดียว
แอปไคลเอ็นต์มี URI เนื้อหาของไฟล์ โดยจะเข้าถึงไฟล์ได้โดยรับ
FileDescriptor
กระบวนการนี้จะรักษาความปลอดภัยของไฟล์ไว้ตราบเท่าที่คุณแยกวิเคราะห์ URI เนื้อหาได้อย่างถูกต้องเท่านั้น
ที่แอปไคลเอ็นต์ได้รับ เมื่อแยกวิเคราะห์เนื้อหา คุณต้องตรวจสอบว่า URI นี้ไม่ได้ชี้ไป
สิ่งที่อยู่นอกไดเรกทอรีที่กำหนด โดยไม่ตรวจสอบ
มีการพยายามทำ path Traversal
มีเพียงแอปไคลเอ็นต์เท่านั้นที่ควรได้รับสิทธิ์เข้าถึงไฟล์ และเฉพาะสิทธิ์ที่ได้รับจาก
แอปเซิร์ฟเวอร์ สิทธิ์เป็นแบบชั่วคราว ดังนั้นเมื่อสแต็กงานของแอปไคลเอ็นต์เสร็จสิ้น
ไม่สามารถเข้าถึงไฟล์ภายนอกแอปเซิร์ฟเวอร์ได้อีกต่อไป
ข้อมูลโค้ดถัดไปจะแสดงวิธีที่แอปไคลเอ็นต์จัดการกับ
Intent
ที่ส่งจากแอปเซิร์ฟเวอร์และวิธีที่แอปไคลเอ็นต์ได้รับ
FileDescriptor
โดยใช้ URI เนื้อหา:
Kotlin
/*
* When the Activity of the app that hosts files sets a result and calls
* finish(), this method is invoked. The returned Intent contains the
* content URI of a selected file. The result code indicates if the
* selection worked or not.
*/
public override fun onActivityResult(requestCode: Int, resultCode: Int, returnIntent: Intent) {
// If the selection didn't work
if (resultCode != Activity.RESULT_OK) {
// Exit without doing anything else
return
}
// Get the file's content URI from the incoming Intent
returnIntent.data?.also { returnUri ->
/*
* Try to open the file for "read" access using the
* returned URI. If the file isn't found, write to the
* error log and return.
*/
inputPFD = try {
/*
* Get the content resolver instance for this context, and use it
* to get a ParcelFileDescriptor for the file.
*/
contentResolver.openFileDescriptor(returnUri, "r")
} catch (e: FileNotFoundException) {
e.printStackTrace()
Log.e("MainActivity", "File not found.")
return
}
// Get a regular file descriptor for the file
val fd = inputPFD.fileDescriptor
...
}
}
Java
/*
* When the Activity of the app that hosts files sets a result and calls
* finish(), this method is invoked. The returned Intent contains the
* content URI of a selected file. The result code indicates if the
* selection worked or not.
*/
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent returnIntent) {
// If the selection didn't work
if (resultCode != RESULT_OK) {
// Exit without doing anything else
return;
} else {
// Get the file's content URI from the incoming Intent
Uri returnUri = returnIntent.getData();
/*
* Try to open the file for "read" access using the
* returned URI. If the file isn't found, write to the
* error log and return.
*/
try {
/*
* Get the content resolver instance for this context, and use it
* to get a ParcelFileDescriptor for the file.
*/
inputPFD = getContentResolver().openFileDescriptor(returnUri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("MainActivity", "File not found.");
return;
}
// Get a regular file descriptor for the file
FileDescriptor fd = inputPFD.getFileDescriptor();
...
}
}
เมธอด openFileDescriptor()
แสดงผล ParcelFileDescriptor
ของไฟล์ ไคลเอ็นต์จากออบเจ็กต์นี้
แอปจะได้รับออบเจ็กต์ FileDescriptor
ซึ่งจะใช้อ่านไฟล์ได้
ดูข้อมูลที่เกี่ยวข้องเพิ่มเติมได้ที่
ตัวอย่างเนื้อหาและโค้ดในหน้าเว็บนี้ขึ้นอยู่กับใบอนุญาตที่อธิบายไว้ในใบอนุญาตการใช้เนื้อหา Java และ OpenJDK เป็นเครื่องหมายการค้าหรือเครื่องหมายการค้าจดทะเบียนของ Oracle และ/หรือบริษัทในเครือ
อัปเดตล่าสุด 2025-07-27 UTC
[[["เข้าใจง่าย","easyToUnderstand","thumb-up"],["แก้ปัญหาของฉันได้","solvedMyProblem","thumb-up"],["อื่นๆ","otherUp","thumb-up"]],[["ไม่มีข้อมูลที่ฉันต้องการ","missingTheInformationINeed","thumb-down"],["ซับซ้อนเกินไป/มีหลายขั้นตอนมากเกินไป","tooComplicatedTooManySteps","thumb-down"],["ล้าสมัย","outOfDate","thumb-down"],["ปัญหาเกี่ยวกับการแปล","translationIssue","thumb-down"],["ตัวอย่าง/ปัญหาเกี่ยวกับโค้ด","samplesCodeIssue","thumb-down"],["อื่นๆ","otherDown","thumb-down"]],["อัปเดตล่าสุด 2025-07-27 UTC"],[],[],null,["# Requesting a shared file\n\nWhen an app wants to access a file shared by another app, the requesting app (the client)\nusually sends a request to the app sharing the files (the server). In most cases, the request\nstarts an [Activity](/reference/android/app/Activity) in the server app that displays the files it can share.\nThe user picks a file, after which the server app returns the file's content URI to the\nclient app.\n\n\nThis lesson shows you how a client app requests a file from a server app, receives the file's\ncontent URI from the server app, and opens the file using the content URI.\n\nSend a request for the file\n---------------------------\n\n\nTo request a file from the server app, the client app calls\n[startActivityForResult](/reference/android/app/Activity#startActivityForResult(android.content.Intent, int)) with an\n[Intent](/reference/android/content/Intent) containing the action such as\n[ACTION_PICK](/reference/android/content/Intent#ACTION_PICK) and a MIME type that the client app\ncan handle.\n\n\nFor example, the following code snippet demonstrates how to send an\n[Intent](/reference/android/content/Intent) to a server app in order to start the\n[Activity](/reference/android/app/Activity) described in [Sharing a file](/training/secure-file-sharing/share-file#SendURI): \n\n### Kotlin\n\n```kotlin\nclass MainActivity : Activity() {\n private lateinit var requestFileIntent: Intent\n private lateinit var inputPFD: ParcelFileDescriptor\n ...\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n requestFileIntent = Intent(Intent.ACTION_PICK).apply {\n type = \"image/jpg\"\n }\n ...\n }\n ...\n private fun requestFile() {\n /**\n * When the user requests a file, send an Intent to the\n * server app.\n * files.\n */\n startActivityForResult(requestFileIntent, 0)\n ...\n }\n ...\n}\n```\n\n### Java\n\n```java\npublic class MainActivity extends Activity {\n private Intent requestFileIntent;\n private ParcelFileDescriptor inputPFD;\n ...\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n requestFileIntent = new Intent(Intent.ACTION_PICK);\n requestFileIntent.setType(\"image/jpg\");\n ...\n }\n ...\n protected void requestFile() {\n /**\n * When the user requests a file, send an Intent to the\n * server app.\n * files.\n */\n startActivityForResult(requestFileIntent, 0);\n ...\n }\n ...\n}\n```\n\nAccess the requested file\n-------------------------\n\n\nThe server app sends the file's content URI back to the client app in an\n[Intent](/reference/android/content/Intent). This [Intent](/reference/android/content/Intent) is passed to the client\napp in its override of [onActivityResult()](/reference/android/app/Activity#onActivityResult(int, int, android.content.Intent)). Once\nthe client app has the file's content URI, it can access the file by getting its\n[FileDescriptor](/reference/java/io/FileDescriptor).\n\n\nFile security is preserved in this process only as long as you properly parse the content URI\nthat the client app receives. When parsing content, you must ensure that this URI does not point\nto anything outside of the intended directory, ensuring that no\n[path traversal](/privacy-and-security/risks/path-traversal) is being attempted.\nOnly the client app should gain access to the file, and only for the permissions granted by the\nserver app. Permissions are temporary, so once the client app's task stack is finished, the\nfile is no longer accessible outside the server app.\n\n\nThe next snippet demonstrates how the client app handles the\n[Intent](/reference/android/content/Intent) sent from the server app, and how the client app gets the\n[FileDescriptor](/reference/java/io/FileDescriptor) using the content URI: \n\n### Kotlin\n\n```kotlin\n/*\n * When the Activity of the app that hosts files sets a result and calls\n * finish(), this method is invoked. The returned Intent contains the\n * content URI of a selected file. The result code indicates if the\n * selection worked or not.\n */\npublic override fun onActivityResult(requestCode: Int, resultCode: Int, returnIntent: Intent) {\n // If the selection didn't work\n if (resultCode != Activity.RESULT_OK) {\n // Exit without doing anything else\n return\n }\n // Get the file's content URI from the incoming Intent\n returnIntent.data?.also { returnUri -\u003e\n /*\n * Try to open the file for \"read\" access using the\n * returned URI. If the file isn't found, write to the\n * error log and return.\n */\n inputPFD = try {\n /*\n * Get the content resolver instance for this context, and use it\n * to get a ParcelFileDescriptor for the file.\n */\n contentResolver.openFileDescriptor(returnUri, \"r\")\n } catch (e: FileNotFoundException) {\n e.printStackTrace()\n Log.e(\"MainActivity\", \"File not found.\")\n return\n }\n\n // Get a regular file descriptor for the file\n val fd = inputPFD.fileDescriptor\n ...\n }\n}\n```\n\n### Java\n\n```java\n /*\n * When the Activity of the app that hosts files sets a result and calls\n * finish(), this method is invoked. The returned Intent contains the\n * content URI of a selected file. The result code indicates if the\n * selection worked or not.\n */\n @Override\n public void onActivityResult(int requestCode, int resultCode,\n Intent returnIntent) {\n // If the selection didn't work\n if (resultCode != RESULT_OK) {\n // Exit without doing anything else\n return;\n } else {\n // Get the file's content URI from the incoming Intent\n Uri returnUri = returnIntent.getData();\n /*\n * Try to open the file for \"read\" access using the\n * returned URI. If the file isn't found, write to the\n * error log and return.\n */\n try {\n /*\n * Get the content resolver instance for this context, and use it\n * to get a ParcelFileDescriptor for the file.\n */\n inputPFD = getContentResolver().openFileDescriptor(returnUri, \"r\");\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n Log.e(\"MainActivity\", \"File not found.\");\n return;\n }\n // Get a regular file descriptor for the file\n FileDescriptor fd = inputPFD.getFileDescriptor();\n ...\n }\n }\n```\n\n\nThe method [openFileDescriptor()](/reference/android/content/ContentResolver#openFileDescriptor(android.net.Uri, java.lang.String))\nreturns a [ParcelFileDescriptor](/reference/android/os/ParcelFileDescriptor) for the file. From this object, the client\napp gets a [FileDescriptor](/reference/java/io/FileDescriptor) object, which it can then use to read the file.\n\nFor additional related information, refer to:\n\n- [Intents and Intent Filters](/guide/components/intents-filters)\n- [Retrieving Data from the Provider](/guide/topics/providers/content-provider-basics#SimpleQuery)"]]