当我选择文件时,我很难调用函数。
当我选择一个文件时,在它开始调用UploadFile
函数然后连接到服务器之前,它开始需要大约10秒钟,所以当我选择添加更多文件时,在它开始调用UploadFile
函数并连接到错误的服务器之前,它将需要一分钟左右的时间。当我添加多个文件时,它应该立即开始调用UploadFile
函数并连接到服务器。
下面是完整的代码:
public class ComposeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final int CHOOSE_FILE_REQUESTCODE = 1;
private RecyclerView mFilesDetailRecyclerView;
private ArrayList<String> mSelectedFilesList = new ArrayList<>();
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CHOOSE_FILE_REQUESTCODE) {
try {
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
Context context = getApplicationContext();
FilePath = RealPathUtil.getRealPath(context, uri);
cursor.moveToFirst();
//mSelectedFilesList.add(cursor.getString(index));
mSelectedFilesList.add(FilePath);
mAdapter.notifyItemInserted(mSelectedFilesList.size());
Log.e("message.......", "caught this.....");
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
} catch (Exception e) {
Toast.makeText(ComposeActivity.this, "Choose any other file", Toast.LENGTH_SHORT).show();
}
}
}
@SuppressLint("StaticFieldLeak")
private class UploadFile extends AsyncTask<Void, Void, Void> {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
try {
String twoHyphens = "--";
String boundary = "*****" + System.currentTimeMillis() + "*****";
String lineEnd = "\r\n";
Log.e("message.......", "FileName...." + FileName);
URL url = new URL("https://www.example.com/fileupload1.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(200);
urlConnection.setReadTimeout(200);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
urlConnection.setRequestProperty("uploaded_file", FileName);
FileInputStream fileInputStream = new FileInputStream(upload_File);
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file" +
"\"; filename=\"" + FileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
Log.e("message.......", "FileName...." + FileName);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//Thread.sleep(5000);
while (bytesRead > 0) {
//int percentage = (int) ((bytesRead / (float) size) * 100);
dataOutputStream.write(buffer, 0, bufferSize);
//dataOutputStream.flush(); //doesn't help
bytesAvailable = fileInputStream.available();
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
int code = urlConnection.getResponseCode();
StringBuilder result = new StringBuilder();
if (code == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
upload_success = result.toString();
}
} catch(SocketTimeoutException e) {
//e.printStackTrace();
if (urlConnection != null) {
urlConnection.disconnect();
cancel(true);
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("message.......", "here....5");
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("message.......", "here....6");
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Log.e("message.......", "here....7");
}
catch (IOException ioException) {
ioException.printStackTrace();
Log.e("message.......", "here....2");
}
catch (Exception e) {
e.printStackTrace();
Log.e("message.......", "here....5");
if (failtoupload == false) {
failtoupload = true;
}
if (sendMail == true) {
sendMail = false;
}
if (UpdateDraft == true) {
UpdateDraft = false;
}
if (saveDraft == true) {
saveDraft = false;
}
Date dt = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String savedDate = dateFormat.format(dt);
draftDB = new DraftDB(mContext);
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
if (attachments.equals("")) {
attachments = null;
}
}
else
{
attachments = join(", ", mSelectedFilesList);
}
if (attachments == null) {
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
}
else
{
attachments = join(", ", mSelectedFilesList);
}
}
String isImportant = "true";
String isRead = "unread";
String UpdateDB = null;
String draftID = null;
if (to == null) {
to = "";
}
if (bcc == null) {
bcc = "";
}
if (cc == null) {
cc = "";
}
if (subject == null) {
subject = "";
}
if (message == null) {
message = "";
}
if (draft_id != null) {
draftID = draft_id;
UpdateDB = "yes";
}
else
{
draftID = "";
UpdateDB = "no";
}
if (draftDB_id == 0) {
draftDB.insertDraft(from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
draftDB_id = draftDB.getID();
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
Log.e("message.......", "here....6");
if (upload_success != null) {
if (upload_success.equals("success")) {
if (mSelectedFilesList.size() > 0) {
mSelectedFilesList.remove(0);
if (draft_id == null) {
new SaveDraft().execute();
}
else if (draft_id != null) {
if (attachment != null) {
if (mSelectedFilesList.size() >= 1) {
attid++;
for (int i = 0; i < mSelectedFilesList.size(); i++) {
String path = mSelectedFilesList.get(0);
FileName = path.substring(path.lastIndexOf("/") + 1);
attachment += " attid: " + String.valueOf(attid) + " filename: " + FileName;
}
}
}
Log.e("message........", "attachment......" + attachment);
new UpdateDrafts().execute();
}
if (mSelectedFilesList.size() >= 1) {
FilePath = mSelectedFilesList.get(0);
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
}
}
//Now time to check the upload_File
if (mSelectedFilesList.size() == 0) {
if (upload_File != null) {
upload_File = null;
}
if (FilePath != null) {
FilePath = null;
}
Log.e("message.......", "sendMail........." + sendMail);
}
if (upload_success != null) {
upload_success = null;
}
}
}
}
@Override
protected void onCancelled() {
super.onCancelled();
this.cancel(true);
}
}
我想做的是,当我选择的文件,并添加更多的文件在我的移动的应用程序,我想调用UploadFile
函数,并连接到我的服务器上传文件在每次我选择的文件。如果服务器没有响应10秒,服务器离线,我想把数据存储在sqlite数据库。
我被告知我应该使用多线程,我也应该使用改造。我不确定是否有可能使用HttpUrlConnection
方法与多线程连接到服务器并上传文件。
你能不能给我一个例子,什么是最好的方法,我可以用来立即调用一个函数,并连接到服务器使用与HttpUrlConnection
,如果这是可能的?
1条答案
按热度按时间qni6mghb1#
尝试为uri获取一个真实的的路径已经是错误的。
删除代码。
然后,不打开FileInputStream,而是打开URI的InputStream