我正在编写一个代码,允许我的用户上传任何类型的文件,这是我的代码:
Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
fileIntent.setType("*/*"); // intent type to filter application based on your requirement
startActivityForResult(fileIntent, 1);
用户可以选择他们的文件,然后通过以下代码获取路径和文件名:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
Uri u = data.getData();
filepath = u.getPath();
filename = u.toString();
chooseFile=true;
}
}
}
这是我将所选文件发送到服务器的代码,我使用assyctask。这是代码;
@Override
protected String doInBackground(String... params) {
if (filepath != null) {//file entekhab shode bud
int serverResponseCode = 0;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String urlServer = getString(R.string.url)+"/getFile.php?id="+sefareshId;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(filepath));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filepath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
Log.v("this", ex.getMessage());
}
return serverResponseCode + "";
} else
return "5";
}
通过运行此代码,我收到此错误:
/document/image:134342: open failed: ENOENT (No such file or directory)
我认为此文件的url路径错误,如何获取正确的文件路径然后上传?
谢谢