Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android客戶端把SD卡文件上傳到服務器端並保存在PC硬盤文件夾中

android客戶端把SD卡文件上傳到服務器端並保存在PC硬盤文件夾中

編輯:關於Android編程

在局域網內,實現從android客戶端把手機SD卡上的文件上傳到PC服務器端,並保存在PC硬盤的指定文件夾下。同時把PC端硬盤文件的目錄和對文件的描述信息保存在mysql數據庫中。


1、客戶端關鍵代碼:

(1)獲得SD卡上的文件

 /**
		 * 獲得文件路徑和狀態信息
		 * 
		 * @return
		 */
		private String getFiles() {
			File path = null;
			
			// 判斷SD卡是否存在可用
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				path = Environment.getExternalStorageDirectory();
				
				File[] files = path.listFiles();
				for (File file : files) {
					// 把路徑如入集合中

					if (file.getPath() != null
							&& (file.getPath()
									.substring(file.getPath().lastIndexOf("/") + 1)
									.equals("DATA_RECORD.pcm"))) {
						return file.getPath();
						
					}
					
				}
			} else {

				Toast.makeText(ASRMainActivity.this, "SD卡不可用!", 300).show();
			}

			return null;

		}

(2)實現文件上傳的方法

private void fileUpLoad() {
		srcPath=getFiles();
		new AsyncTask() {
			
			String end = "\r\n";
			String twoHyphens = "--";
			String boundary = "****************";
			HttpURLConnection con;
			URL url = null;
			InputStreamReader isr = null;
			FileInputStream fis;
			DataOutputStream dos;

			@Override
			protected Void doInBackground(Void... params) {
				String record_content=mSharedPreferences.getString("content","");
				Log.i("測試",record_content);
				try {
					// 首先指定服務器的路徑URL
					url = new URL(
							"http://192.168.1.109:8080/MFCC/SpeechRecognizeAction?action_flag=upload&record_content="+record_content);
					// 打開一個連接
					con = (HttpURLConnection) url.openConnection();
					// 設置一些屬性
					con.setDoInput(true);
					con.setDoOutput(true);
					con.setDefaultUseCaches(false);
					con.setRequestMethod("POST");
					con.setRequestProperty("Connection", "Keep-Alive");
					con.setRequestProperty("Charset", "UTF-8");
					con.setRequestProperty("Content-Type",
							"multipart/form-data;boundary=" + boundary);
					con.setReadTimeout(3000);
//
				
 
					// 創建一個新的數據輸出流,將數據寫入指定基礎輸出流
					dos = new DataOutputStream(con.getOutputStream());
					// 將字符串按字節順序 寫出 到基礎輸出流中
					// dos.writeBytes("Content-Disposition: form-data; name=\"uploads\";filename=1.txt");
					// dos.writeBytes("Content-Disposition: form-data;");
					dos.writeBytes(twoHyphens + boundary + end);
					dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
							+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
							+ "\"" + end);
					Log.i("tag",
							"Content-Disposition: form-data; name=\"file\"; filename=\""
									+ srcPath.substring(srcPath
											.lastIndexOf("/") + 1) + "\"" + end);
					dos.writeBytes(end);
					// dos.writeBytes("1.txt");
					// dos.writeBytes("Jonny-Resume.docx");
					// 讀取寫到輸出流中的數據
					fis = new FileInputStream(srcPath);
					byte[] buffer = new byte[8192]; // 8k
					int count = 0;
					count = fis.read(buffer);
					Log.i("tag", count + "  ********************");
					while ((count = fis.read(buffer)) != -1) {
						dos.write(buffer, 0, count);
						Log.i("tag", "ok");
					}
					fis.close();
					dos.writeBytes(end);
					dos.writeBytes(twoHyphens + boundary + twoHyphens + end);

					dos.flush();

					// 反饋給客戶端的信息
					InputStream is = con.getInputStream();

					isr = new InputStreamReader(is, "utf-8");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				String result2 = null;
				StringBuffer stringBuffer = null;
				BufferedReader br = null;
				if (isr == null) {
					return;
				}
				try {
					br = new BufferedReader(isr);
					stringBuffer = new StringBuffer();

					while ((result2 = br.readLine()) != null) {
						stringBuffer.append(result2);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

				} finally {

					if (dos != null) {
						try {
							dos.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

				}
				if (stringBuffer != null)
					Toast.makeText(ASRMainActivity.this,
							new String(stringBuffer), Toast.LENGTH_LONG).show();
				btn_uploadFile.setEnabled(true);

			}

		}.execute();

	}

服務器端關鍵代碼:

/**
	 * 上傳文件到PC,並把相關的文件信息寫如數據庫
	 * @param request
	 * @param response
	 */
	private void uploadFile(HttpServletRequest request, HttpServletResponse response) {
		String content = request.getParameter("record_content");
		PrintWriter printWriter=null;
	 
		
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();// 實例化一個文件工廠
		// 構建一個文件上傳類
		ServletFileUpload servletFileUpload = new ServletFileUpload(
				diskFileItemFactory);// 生成一個處理文件上傳的servlet對象
		servletFileUpload.setFileSizeMax(3 * 1024 * 1024);
		servletFileUpload.setSizeMax(6 * 1024 * 1024);// 上傳文件總大小

		try {
			// 分析請求,並得到上傳文件的FileItem對象
			printWriter=response.getWriter();
			List items = servletFileUpload.parseRequest(request);
			Iterator e = items.iterator();
			while (e.hasNext()) {
				FileItem item = e.next();

				if (item.getName() != null && !item.getName().equals("")) {
					

					File file = new File("E://rawSpeechRecordData//");
					File newFile = null;

					if (!file.exists()) {
						file.mkdir();
						if (file.isDirectory()) {
							SimpleDateFormat format = new SimpleDateFormat(
									"yyyyMMddHHmmss");
							String date = format.format(new Date(System
									.currentTimeMillis()));
							newFile = new File(
									"E://rawSpeechRecordData//rawdata" + date
											+".pcm");

							item.write(newFile);
							
							//數據存入數據庫
							System.out.println("**********************"
									+ newFile.getPath());

							mFileInfoDao.addFilePathInfos(newFile.getPath(), content);
							printWriter.write("數據提交成功!");
							System.out.println(file);
							System.out
									.println("Content-Disposition: form-data; name=\"file\"; filename=\"");
							System.out.println("**********************");
							
						}
						
					} else {
						if (file.isDirectory()) {
							SimpleDateFormat format = new SimpleDateFormat(
									"yyyyMMddHHmmss");
							String date = format.format(new Date(System
									.currentTimeMillis()));
							newFile = new File(
									"E://rawSpeechRecordData//rawdata" + date
											+".pcm");


							item.write(newFile);
							//數據存入數據庫
							mFileInfoDao.addFilePathInfos(newFile.getPath(), content);
							printWriter.write("數據提交成功!");
							System.out.println("**********************"
									+ newFile.getPath());
							System.out.println(file);
							System.out
									.println("Content-Disposition: form-data; name=\"file\"; filename=\"");
							System.out.println("**********************");
						}
					}

				}
			}
			
			

		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



3、數據庫設計代碼:

(1)數據庫操作接口定義

public interface FileInfoDao {
	/**
	 * 添加文件路徑到數據庫
	 * @param filePath 文件路徑
	 * @param content錄音的詳細信息
	 */
	public void addFilePathInfos(String filePath,String content);
	/**
	 * 刪除一條錄音的路徑信息
	 * @param content 錄音的詳細信息
	 */
	public void deleteAFilePathInfo(String content);
	/**
	 * 刪除所有的錄音文件路徑
	 */
	public void deleteAllFilePathInfos();
	/**
	 * 查詢所有的文件路徑
	 * @return
	 */
	public List> getAllFilePaths();

}

(2)數據庫操作實現類

public class FileInfoDaoimpl implements FileInfoDao {
	// 表示定義數據庫的用戶名
	private final String USERNAME = "root";
	// 定義數據庫的密碼
	private final String PASSWORD = "admin";
	// 定義數據庫的驅動信息
	private final static String DRIVER = "com.mysql.jdbc.Driver";
	// 定義數據庫連接
	private static Connection mConnection;
	// 定義訪問數據庫的地址
	private final String URL = "jdbc:mysql://192.168.1.109:3306/fileinfos";
	// 定義sql語句的執行對象
	private PreparedStatement pstmt;
	// 定義查詢返回的結果集合
	private ResultSet resultSet;

	public FileInfoDaoimpl() {
		// 加載驅動
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void addFilePathInfos(String filePath, String content) {
		PreparedStatement preparedStatement = null;
		try {
			// 獲得數據庫連接
			mConnection = DriverManager.getConnection(URL, "root", "admin");
			// 獲得SQL語句執行對象
			preparedStatement = mConnection
					.prepareStatement("insert into filepaths(file_path,record_content) values(?,?)");
			// 設置參數
			preparedStatement.setString(1, filePath);
			preparedStatement.setString(2, content);
			// 執行SQL語句
			preparedStatement.execute();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (preparedStatement != null) {
				try {
					preparedStatement.close();
					preparedStatement = null;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			if (mConnection != null) {
				try {
					mConnection.close();
					mConnection = null;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}

	}

	@Override
	public void deleteAFilePathInfo(String content) {
		PreparedStatement preparedStatement=null;
		//獲得數據庫連接
		try {
			mConnection=DriverManager.getConnection(URL,"root","admin");
			//獲得SQL語句執行對象
			 preparedStatement=mConnection.prepareStatement("delete from filepaths where record_content=?");
			//設置參數
			preparedStatement.setString(1, content);
			preparedStatement.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(preparedStatement!=null){
				try {
					preparedStatement.close();
					preparedStatement=null;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			if(mConnection!=null){
				try {
					mConnection.close();
					mConnection=null;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}

	}

	@Override
	public void deleteAllFilePathInfos() {
		PreparedStatement preparedStatement=null;
		try {
			mConnection=DriverManager.getConnection(URL, USERNAME,PASSWORD);
			preparedStatement=mConnection.prepareStatement("delete from filepaths");
			preparedStatement.execute();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
			if(preparedStatement!=null){
				try {
					preparedStatement.close();
					preparedStatement=null;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			if(mConnection!=null){
				try {
					mConnection.close();
					mConnection=null;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}

	}

	@Override
	public List> getAllFilePaths() {
		PreparedStatement preparedStatement=null;
		List> results=new ArrayList>();
		HashMap result=null;
		try {
			mConnection=DriverManager.getConnection(URL, USERNAME, PASSWORD);
			preparedStatement=mConnection.prepareStatement("select file_path,record_content from filepaths");
			//查詢
			resultSet= preparedStatement.executeQuery();
			
			while(resultSet.next()){
				result=new HashMap();
				result.put("filepath", resultSet.getString("file_path"));
				result.put("record_content", resultSet.getString("record_content"));
				results.add(result);
				result=null;
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
			if(preparedStatement!=null){
				try {
					preparedStatement.close();
					preparedStatement=null;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			if(mConnection!=null){
				try {
					mConnection.close();
					mConnection=null;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		return results;
	}

}

(3)數據庫操作對象的靜態工廠方法(單例模式)

public class FilePathInfosDaoFactory {
	private static FileInfoDao mFileInfoDaoimpl;

	/**
	 * 獲得數據庫操作單例對象
	 * 
	 * @return
	 */
	public static FileInfoDao getInstanse() {

		if (mFileInfoDaoimpl == null) {
			mFileInfoDaoimpl = new FileInfoDaoimpl();
		}
		return mFileInfoDaoimpl;
	}

}



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved