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

2017/05/22 11:12
阅读数 104

在局域网内,实现从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();
 
    }</void,>

 

服务器端关键代码:

/**
     * 上传文件到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();
        }
    }</fileitem></fileitem>

 

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();
 
}</map<string,string>

 

(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;
    }
 
}</string,></string,string></map<string,string></map<string,string></map<string,string>

 

(3)数据库操作对象的静态工厂方法(单例模式)

public class FilePathInfosDaoFactory {
    private static FileInfoDao mFileInfoDaoimpl;
 
    /**
     * 获得数据库操作单例对象
     * 
     * @return
     */
    public static FileInfoDao getInstanse() {
 
        if (mFileInfoDaoimpl == null) {
            mFileInfoDaoimpl = new FileInfoDaoimpl();
        }
        return mFileInfoDaoimpl;
    }
 
}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部