0
메신저 업로드 파일과 진행 막대를 사용하려고 메신저를 작동하지 :해서 ProgressDialog 바
@Override
public void onClick(View v) {
if(v== ivAttachment){
//on attachment icon click
showFileChooser();
}
if(v== bUpload){
//on upload button Click
if(selectedFilePath != null){
dialog = new ProgressDialog(upload.this);
dialog.setMax(100);
dialog.setMessage("Subiendo Archivo...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.show();
//dialog.show(upload.this,"","Subiendo Archivo...",true);
new Thread(new Runnable() {
@Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedFilePath);
}
}).start();
}else{
Toast.makeText(upload.this,"Escoge un archivo",Toast.LENGTH_SHORT).show();
}
}
}
다음을 UploadFile (selectedFilePath);
이//android upload file to server
public int uploadFile(final String selectedFilePath){
int serverResponseCode = 0;
File sourceFile = new File(selectedFilePath);
int totalSize = (int)sourceFile.length();
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length-1];
if (!selectedFile.isFile()){
dialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
}
});
return 0;
}else{
try{
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file",selectedFilePath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ selectedFilePath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
int totalBytesWritten = 0;
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0) {
//write the bytes read from inputstream
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytesWritten += bytesRead;
if (dialog != null) {
dialog.setProgress((int)(totalBytesWritten/ totalSize * 100));
}
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
@Override
public void run() {
tvFileNames.setText("Sigue el link para ver tu archivo:");
tvFileName.setText(Html.fromHtml("<a href=\"https://cloud.dattasolutions.com.mx/app/uploads/" + fileName + "\"><font color=\"red\">" + fileName + "</font></a> "));
tvFileName.setMovementMethod(LinkMovementMethod.getInstance());
// tvFileName.setTextColor(Color.BLUE);
//tvFileName.setText("Escoger otro archivo");
ivAttachment.setVisibility(View.VISIBLE);
vView1.setVisibility(View.GONE);
tvFileNames.setVisibility(View.VISIBLE);
ivAttachment.setImageResource(R.drawable.attach_icon);
android.view.ViewGroup.LayoutParams layoutParams = ivAttachment.getLayoutParams();
layoutParams.width = 300;
layoutParams.height = 300;
ivAttachment.setLayoutParams(layoutParams);
//POSISION TEXTO
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.ivAttachment);
params.setMargins(0, 73, 0 ,0);
RelativeLayout.LayoutParams params1= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.BELOW, R.id.tv_file_names);
params1.setMargins(0, 123, 0 ,0);
tvFileNames.setLayoutParams(params);
tvFileName.setLayoutParams(params1);
Toast.makeText(getApplicationContext(),
"Archivo subido correctamente!", Toast.LENGTH_LONG)
.show();
}
});
}
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(upload.this,"File Not Found",Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(upload.this, "URL error!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(upload.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
return serverResponseCode;
}
}
문제가 여기에 있습니다 : : 바로 여기
int totalBytesWritten = 0;
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0) {
//write the bytes read from inputstream
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytesWritten += bytesRead;
if (dialog != null) {
dialog.setProgress((int)(totalBytesWritten/ totalSize * 100));
}
: 여기서 시작은 내 코드입니다
경우 (! 대화 = NULL) { dialog.setProgress ((INT) (totalBytesWritten/totalSize * 100)); }
proggress 바는 100 %의 모든 시간
코드의 일부를 사용했지만 진행률 백분율 14/100과 같은 고정이 있습니다. 여기에 다른 설명이 있습니다. https://stackoverflow.co m/questions/46559312/progressdialog-bar-get-freeze –
예. 업데이트를 호출 할 때 중요합니다. 백그라운드 스레드에서 전화를 걸고 예를 들어 밀리 초마다 업데이트하지 않도록하고 싶습니다. 너무 자주 업데이트하면 정지 될 수 있습니다. – Sam