1

我可以使用以下代码将文本文件附加到电子邮件中:

String fileName = "test.txt";
path = "file://" + Environment.getExternalStorageDirectory() + "/" + fileName;

Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
startActivity(Intent.createChooser(sendIntent, "Email"));

但是,通过 gmail 发送的电子邮件不包含附件,如果fileName="test#.txt".

我尝试使用 URLEncoder 对路径进行编码,如下所示,但这不适用于“text.txt”或“text#.txt”。

我可能在这里遗漏了一些简单的东西,但是我应该如何使用特殊字符对文件路径进行编码以发送意图?

String fileName = "test.txt";
// String fileName = "test#.txt";

String path = "file://" + Environment.getExternalStorageDirectory() + "/" + fileName;
String encPath = URLEncoder.encode(path);

Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(encPath));
startActivity(Intent.createChooser(sendIntent, "Email"));
4

1 回答 1

1

那是因为您没有正确编码 URL。您对完整的 URL 进行了编码,而不是仅对文件名进行编码,结果如下:

file://te#st.txt
file%3A%2F%2Fte%23st.txt

试试这个:

String path = "file://" + Environment.getExternalStorageDirectory() + "/";
path += URLEncoder.encode( fileName );
于 2012-05-25T19:43:46.827 回答