|
|
|
Android - ช่วยดูโค้ดให้ทีค่ะ จะ upload ขึ้น server แต่ upload ไม่ได้มันบอกว่าไม่เจอไฟล์ |
|
|
|
|
|
|
|
ช่วยทีค่ะ คือตอนนี้อัพโหลดไฟล์ไม่ขึ้น
มันโชว์ขึ้นมาบอกว่าไม่มีไฟล์ให้เช็คpathให้ถูก
แต่พอตรวจสอบไฟล์แล้วมันก็เจอ
Code (Android-Java)
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
FTPClient client;
private ListView lstView;
private Handler handler = new Handler();
List<String> listFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
client = connectWithFTP();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
task getson = new task();
getson.execute();
listFile = checkFiles(client);
System.out.println("status :: " + client);
lstView = (ListView)findViewById(R.id.listView1);
lstView.setAdapter(new ListAdapter(this,listFile));
// Check All
Button btnCheckAll = (Button) findViewById(R.id.btnCheckAll);
btnCheckAll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int count = lstView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
LinearLayout itemLayout = (LinearLayout)lstView.getChildAt(i); // Find by under LinearLayout
CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.ColChk);
checkbox.setChecked(true);
}
}
});
// Clear All
Button btnClearAll = (Button) findViewById(R.id.btnClearAll);
btnClearAll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int count = lstView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
LinearLayout itemLayout = (LinearLayout)lstView.getChildAt(i); // Find by under LinearLayout
CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.ColChk);
checkbox.setChecked(false);
}
}
});
// Get Item Checked
Button btnGetItem = (Button) findViewById(R.id.btnGetItem);
btnGetItem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int count = lstView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
LinearLayout itemLayout = (LinearLayout)lstView.getChildAt(i); // Find by under LinearLayout
CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.ColChk);
if(checkbox.isChecked())
{
Log.d("Item "+String.valueOf(i), checkbox.getTag().toString());
Toast.makeText(MainActivity.this,checkbox.getTag().toString() ,Toast.LENGTH_LONG).show();
}
}
}
});
}
public FTPClient connectWithFTP() throws IOException{
client = new FTPClient();
try {
client.connect("Server", 21);
client.login("username", "password");
System.out.println("status :: " + client.getReplyString());
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new Exception("Connect failed: " + client.getReplyString());
}
try {
client.enterLocalPassiveMode();
if (!client.setFileType(FTP.BINARY_FILE_TYPE)) {
Log.v(getClass().toString(), "Setting binary file type failed.");
}
} catch(Exception e) {
e.printStackTrace();
}
checkFiles(client);
} catch (Exception e) {
System.out.println("status :: " + client.getReplyString());
}
return client;
}
private class task extends AsyncTask <Void, Void, FTPClient> {
@Override
protected void onPreExecute() {
// Do stuff before the operation
}
@Override
protected FTPClient doInBackground(Void... params) {
FTPClient ftp = null;
try {
ftp = connectWithFTP();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void disconnectWithFTP() throws IOException{
client.logout();
client.disconnect();
}
private List <String> checkFiles(FTPClient clients){
List <String> it = new ArrayList <String>();
try {
FTPFile[] ftpFiles = clients.listFiles();
int length = ftpFiles.length;
for (int i = 0; i < length; i++) {
String name = ftpFiles[i].getName();
//Calendar date = ftpFiles[i].getTimestamp();
Log.v("aasd", name );
it.add (name);
}
} catch(Exception e) {
e.printStackTrace();
}
return it ;
}
public class ListAdapter extends BaseAdapter
{
private Context context;
private List <String> lis;
public ListAdapter(Context c, List<String> li)
{
//super( c, R.layout.activity_column, R.id.rowTextView, );
// TODO Auto-generated method stub
context = c;
lis = li;
}
public int getCount() {
// TODO Auto-generated method stub
return listFile.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_colum, null);
}
// ColName
TextView txtName=(TextView) convertView.findViewById(R.id.ColCode);
String strPath = lis.get(position).toString();
String fileName = strPath.substring( strPath.lastIndexOf('/')+1, strPath.length());
// System.out.println("file length :: " + fileName +" "+length);
File file = new File(strPath);
long length = file.length();
txtName.setPadding(3, 0, 0, 0);
txtName.setText(" Name :" + fileName + " ( "+ length/1024 +" KB.)");
// ColChk
CheckBox Chk = (CheckBox) convertView.findViewById(R.id.ColChk);
Chk.setTag(listFile.get(position));
// ColStatus
final TextView txtStatus = (TextView) convertView.findViewById(R.id.ColStatus);
txtStatus.setPadding(3, 0, 0, 0);
txtStatus.setText("...");
// progressBar
final ProgressBar progress = (ProgressBar)convertView.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
progress.setPadding(0, 0, 0, 0);
//btnUpload
final Button btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
btnUpload.setTextColor(Color.BLACK);
btnUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Upload
btnUpload.setEnabled(false);
btnUpload.setTextColor(Color.GRAY);
startUpload(position);
}
});
return convertView;
}
}
//Upload
public void startUpload(final int position) {
Runnable runnable = new Runnable() {
public void run() {
handler.post(new Runnable() {
public void run() {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE);
// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
status.setText("Uploading..");
new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}
// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {
String resServer;
int position;
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
position = Integer.parseInt(params[0]);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int resCode = 0;
String resMessage = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// File Path
String strSDPath = listFile.get(position).toString();
// Upload to PHP Script
String strUrlServer = "http://158.108.207.101/android/uploadFile.php";
try {
/** Check file on SD Card ***/
File file = new File(strSDPath);
//System.out.println("name==> "+ file);
if(!file.exists())
{
resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
System.out.println("name==> "+ file);
return null;
}
FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));
URL url = new URL(strUrlServer);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream outputStream = new DataOutputStream(conn
.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\""
+ strSDPath + "\"" + 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);
// Response Code and Message
resCode = conn.getResponseCode();
if(resCode == HttpURLConnection.HTTP_OK)
{
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read = 0;
while ((read = is.read()) != -1) {
bos.write(read);
}
byte[] result = bos.toByteArray();
bos.close();
resMessage = new String(result);
}
Log.d("resCode=",Integer.toString(resCode));
Log.d("resMessage=",resMessage.toString());
fileInputStream.close();
outputStream.flush();
outputStream.close();
resServer = resMessage.toString();
System.out.println("name yyyy ==> "+ file);
} catch (Exception ex) {
// Exception handling
return null;
}
return null;
}
protected void onPostExecute(Void unused) {
statusWhenFinish(position,resServer);
}
}
// When UPload Finish
protected void statusWhenFinish(int position, String resServer) {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
/** Get result from Server (Return the JSON Code)
* StatusID = ? [0=Failed,1=Complete]
* Error = ? [On case error return custom error message]
*
* Eg Upload Failed = {"StatusID":"0","Error":"Cannot Upload file!"}
* Eg Upload Complete = {"StatusID":"1","Error":""}
*/
/*** Default Value ***/
String strStatusID = "0";
String strError = "Unknow Status!";
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Status
if(strStatusID.equals("0"))
{
// When update Failed
status.setText("Upload Failed. ("+ strError +")");
status.setTextColor(Color.RED);
// Enabled Button again
Button btnUpload = (Button) v.findViewById(R.id.btnUpload);
btnUpload.setText("Re-try");
btnUpload.setTextColor(Color.RED);
btnUpload.setEnabled(true);
}
else
{
status.setText("Upload Completed.");
status.setTextColor(Color.GREEN);
}
}
/* @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
*/
}
Tag : Mobile, Android, JAVA, Mobile
|
ประวัติการแก้ไข 2014-01-24 21:54:15
|
|
|
|
|
Date :
2014-01-24 21:52:07 |
By :
iamillusion |
View :
1278 |
Reply :
5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
http://158.108.207.101/android/uploadFile.php
แก้ส่วนนี้แล้วค่ะ แต่ก็ยัง upload ไม่ได้ T^T
|
|
|
|
|
Date :
2014-01-25 19:09:34 |
By :
iamillusion |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ไม่รู้จะช่วยยังไง
|
|
|
|
|
Date :
2014-01-26 07:45:14 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 01
|