Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > Mobile > Mobile Forum > Android - ช่วยดูโค้ดให้ทีค่ะ จะ upload ขึ้น server แต่ upload ไม่ได้มันบอกว่าไม่เจอไฟล์



 

Android - ช่วยดูโค้ดให้ทีค่ะ จะ upload ขึ้น server แต่ upload ไม่ได้มันบอกว่าไม่เจอไฟล์

 



Topic : 105007



โพสกระทู้ ( 17 )
บทความ ( 0 )



สถานะออฟไลน์




ช่วยทีค่ะ คือตอนนี้อัพโหลดไฟล์ไม่ขึ้น

มันโชว์ขึ้นมาบอกว่าไม่มีไฟล์ให้เช็ค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
Move To Hilight (Stock) 
Send To Friend.Bookmark.
Date : 2014-01-24 21:52:07 By : iamillusion View : 1223 Reply : 5
 

 

No. 1



โพสกระทู้ ( 74,058 )
บทความ ( 838 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์
Twitter Facebook

Quote:
http://158.108.207.101/android/uploadFile.php


ลองสร้างไฟล์ form ของ php แล้ว Upload ทดสอบดูครับ






แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2014-01-25 06:49:52 By : mr.win
 


 

No. 2



โพสกระทู้ ( 17 )
บทความ ( 0 )



สถานะออฟไลน์


https://www.thaicreate.com/mobile/android-upload-file-show-items-progressbar-listview.html


ลองทำตามนี้มัน upload ได้ค่ะ


แล้วอยากทราบว่า ถ้าเราจะดู path ไฟล์ที่ดึงมาจาก server ทำยังไงอ่าคะ เพราะมันขึ้นแจ้งให้เช็ค path อ่าค่ะ
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2014-01-25 09:55:28 By : iamillusion
 

 

No. 3



โพสกระทู้ ( 74,058 )
บทความ ( 838 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์
Twitter Facebook

Quote:
http://158.108.207.101/android/uploadFile.php


ทดสอบเรียกผ่าน Web Browser ยังไม่ได้เลยครับ
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2014-01-25 16:00:29 By : mr.win
 


 

No. 4



โพสกระทู้ ( 17 )
บทความ ( 0 )



สถานะออฟไลน์


http://158.108.207.101/android/uploadFile.php

แก้ส่วนนี้แล้วค่ะ แต่ก็ยัง upload ไม่ได้ T^T
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2014-01-25 19:09:34 By : iamillusion
 


 

No. 5



โพสกระทู้ ( 74,058 )
บทความ ( 838 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์
Twitter Facebook

ไม่รู้จะช่วยยังไง
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2014-01-26 07:45:14 By : mr.win
 

   

ค้นหาข้อมูล


   
 

แสดงความคิดเห็น
Re : Android - ช่วยดูโค้ดให้ทีค่ะ จะ upload ขึ้น server แต่ upload ไม่ได้มันบอกว่าไม่เจอไฟล์
 
 
รายละเอียด
 
ตัวหนา ตัวเอียง ตัวขีดเส้นใต้ ตัวมีขีดกลาง| ตัวเรืองแสง ตัวมีเงา ตัวอักษรวิ่ง| จัดย่อหน้าอิสระ จัดย่อหน้าชิดซ้าย จัดย่อหน้ากึ่งกลาง จัดย่อหน้าชิดขวา| เส้นขวาง| ขนาดตัวอักษร แบบตัวอักษร
ใส่แฟลช ใส่รูป ใส่ไฮเปอร์ลิ้งค์ ใส่อีเมล์ ใส่ลิ้งค์ FTP| ใส่แถวของตาราง ใส่คอลัมน์ตาราง| ตัวยก ตัวห้อย ตัวพิมพ์ดีด| ใส่โค้ด ใส่การอ้างถึงคำพูด| ใส่ลีสต์
smiley for :lol: smiley for :ken: smiley for :D smiley for :) smiley for ;) smiley for :eek: smiley for :geek: smiley for :roll: smiley for :erm: smiley for :cool: smiley for :blank: smiley for :idea: smiley for :ehh: smiley for :aargh: smiley for :evil:
Insert PHP Code
Insert ASP Code
Insert VB.NET Code Insert C#.NET Code Insert JavaScript Code Insert C#.NET Code
Insert Java Code
Insert Android Code
Insert Objective-C Code
Insert XML Code
Insert SQL Code
Insert Code
เพื่อความเรียบร้อยของข้อความ ควรจัดรูปแบบให้พอดีกับขนาดของหน้าจอ เพื่อง่ายต่อการอ่านและสบายตา และตรวจสอบภาษาไทยให้ถูกต้อง

อัพโหลดแทรกรูปภาพ

Notice

เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ
อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง

   
  เพื่อความปลอดภัยและการตรวจสอบ กระทู้ที่แทรกไฟล์อัพโหลดไฟล์จากที่อื่น อาจจะถูกลบทิ้ง
 
โดย
อีเมล์
บวกค่าให้ถูก
<= ตัวเลขฮินดูอารบิก เช่น 123 (หรือล็อกอินเข้าระบบสมาชิกเพื่อไม่ต้องกรอก)







Exchange: นำเข้าสินค้าจากจีน, Taobao, เฟอร์นิเจอร์, ของพรีเมี่ยม, ร่ม, ปากกา, power bank, แฟลชไดร์ฟ, กระบอกน้ำ

Load balance : Server 04
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่