android客户端把SD卡文件上传到服务器端并保存在PC硬盘文件夹中

在局域网内,实现从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<Void, Void, Void>() {

			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<FileItem> items = servletFileUpload.parseRequest(request);
			Iterator<FileItem> 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<Map<String,String>> 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<Map<String,String>> getAllFilePaths() {
		PreparedStatement preparedStatement=null;
		List<Map<String,String>> results=new ArrayList<Map<String,String>>();
		HashMap<String,String> 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<String, String>();
				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;
	}

}
时间: 2024-08-08 03:06:03

android客户端把SD卡文件上传到服务器端并保存在PC硬盘文件夹中的相关文章

将android客户端的错误日志压缩上传到服务器

原文:将android客户端的错误日志压缩上传到服务器 源代码下载地址:http://www.zuidaima.com/share/1550463760370688.htm

Android测试读写sd卡文件与写sd卡文件耗时

测试从sd卡读1k大小的文件,再写1k大小的文件,由于处理耗时很短,所以循环500次,查看耗时:测试写1k大小的文件,直接在内存构造一个1k的buffer,将这个buffer直接写到文件,同样循环500次,查看耗时. 思路:首先读写文件,建立文件输入输出流,然后将读取的数据直接写入文件,打印时间戳,查看耗时:只写文件,新建一个1k的buffer,然后用文件输出流写入文件,打印时间戳,查看耗时. 直接上代码: 1 package com.example.ghimtim.myapplication;

在asp.net中用客户端上传控件上传文件( 需要注意的)

在asp.net中使用<inpu nme=“file” type=“file”>客户端控件上传文件, 代码大致如下: for(int i=0; i< Request.Files.Count; i++) //这里就是获取不到file的个数 { if(Request.Files[i].ContentLength > 0) { Response.Write (Request.Files [i].FileName ); } } 在我的页面中,Request.Files.Count怎么弄都是

android选择图片或拍照图片上传到服务器(包括上传参数)

From:http://blog.csdn.net/springsky_/article/details/8213898具体上传代码: 1.选择图片和上传界面,包括上传完成和异常的回调监听 [java] view plaincopy package com.spring.sky.image.upload; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.app.

android app崩溃日志收集以及上传

源码获取请到github:https://github.com/DrJia/AndroidLogCollector 已经做成sdk的形式,源码已公开,源码看不懂的请自行google. 如果想定制适应自己app的sdk请自行fork. AndroidLogCollector android app崩溃日志收集sdk 1.0 作者:贾博士 崩溃日志收集方法: 1.LogCollector是lib包,在需要添加崩溃日志sdk的工程中导入此包. 2.导入lib后,在自己的工程的AndroidManife

006-文件上传校验与直接下载

->说明:使用http协议只适合传输小文件,如果想传递大文件,则需要使用插件或者客户端程序(使用ftp协议)->客户端操作<1>为表单添加属性:enctype="multipart/form-data"<2>在表单中添加控件:<input type="file" name="f1"/> <3>表单必须使用post提交方式->服务器端操作<1>使用Request.File

Windows Phone8.1中SD卡文件的读取写入方法汇总

起初我想从SD卡上读取文件可以从两个方面着手吧: 1.通过文件选择器FileOpenPicker,来逐层到手机找到需要读取的文件,然后点击直接读取显示内容 2.直接到SD卡中读取文件 第一种方法逻辑有些复杂,设计到应用暂时的挂起和恢复,这篇博客不深究这种方法 第二种方法,相对于来说逻辑就比较简单了.只要获取到SD卡对象,遍历里面的文件或者直接指定某一个文件夹,接下 来就是读取文件内容或文件夹中的内容了. 对于上面的两种方法,作为初学者的我最近都尝试了好几遍,着实感觉学到了好多.多次逛博客,贴吧,

Android利用网络编程HttpClient批量上传(一个)

请尊重他人的劳动成果.转载请注明出处:Android网络编程之使用HttpClient批量上传文件 我曾在<Android网络编程之使用HTTP訪问网络资源>一文中介绍过HttpCient的使用,这里就不在累述了,感兴趣的朋友能够去看一下.在这里主要介绍怎样通过HttpClient实现文件上传. 1.预备知识: 在HttpCient4.3之前上传文件主要使用MultipartEntity这个类,但如今这个类已经不在推荐使用了. 随之替代它的类是MultipartEntityBuilder. 以

B/S----文件上传,图片水印,验证码

文件上传: //把相对路径变成绝对路径.string absolutePath = Server.MapPath(relativePath); FileUpload控件:    属性:        FileName:文件名        HasFile:bool 是否选中了文件        FileBytes:要上传文件的二进制数据    方法:        SaveAs(string 绝对路径):上传,另存为. 一.上传到硬盘文件夹(一)传单个文件    第一步:准备好文件及路径: