The Android client uploads the SD card file to the server side and saves it in the PC hard drive folder

Source: Internet
Author: User

In the LAN, the implementation from the Android client to the mobile phone SD card files uploaded to the PC server side, and saved in the PC hard drive under the specified folder. At the same time, the PC-side hard disk file directory and the file description information stored in the MySQL database.


1, the client key code:

(1) Get the files on the SD card

/** * Get file path and status information *  * @return */private String getFiles () {File path = null;//Determine if there is an SD card available if (environment.getexternals Toragestate (). Equals (environment.media_mounted)) {path = Environment.getexternalstoragedirectory (); file[] files = path.listfiles (); for (File file:files) {//Put the path into the collection if (File.getpath ()! = null&& (File.getpath (). s Ubstring (File.getpath (). LastIndexOf ("/") + 1). Equals ("DATA_RECORD.PCM")) {return File.getpath ();}}} else {toast.maketext (asrmainactivity.this, "SD card not available!"). Show (); return null;}

(2) How to implement file upload

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; @Overrideprotected void doinbackground (void ... params) {String Record_ Content=msharedpreferences.getstring ("Content", ""); LOG.I ("Test", record_content); try {//First specify the path of the server Urlurl = new URL ("Http://192.168.1.109:8080/MFCC/SpeechRecognizeAction ? action_flag=upload&record_content= "+record_content);//Open a connection con = (httpurlconnection) url.openconnection (); /Set some properties 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);// Creates a new data output stream, writes data to the specified base output stream dos = new DataOutputStream (CON.GEtoutputstream ());//Writes the string in byte order to the underlying output stream//Dos.writebytes ("Content-disposition:form-data; Name=\ "uploads\"; filename=1.txt ");//Dos.writebytes (" content-disposition:form-data; "); Dos.writebytes (twohyphens + boundary + end);d os.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 ";d os.writebytes (end);//Dos.writebytes (" 1.txt ");//Dos.writebytes (" Jonny-resume.docx ");// Read data written to the output stream FIS = new FileInputStream (Srcpath); byte[] buffer = new byte[8192]; 8kint 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 ();d os.writebytes (end);d os.writebytes (twohyphens + boundary + twohyphens + end);d Os.flush ();// Feedback to client information InputStream is = Con.getinputstream (); ISR= New InputStreamReader (IS, "utf-8");} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return null;} @Overrideprotected 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) {Stringbuffe R.append (RESULT2);}}  catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {if (Dos! = null) {try {dos.close ()}; catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (FIS! = null) {try {fis.close ()} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} if (StringBuffer! = null) Toast.maketext (asrmainactivity.this,new String (StringBuffer), Toast.length_long). Show (); Btn_uploadfile.setenabled (True);}}. Execute ();}

Server-side Key code:

/** * Upload files to pc and write related file information like database * @param request * @param response */private void UploadFile (HttpServletRequest request, Http Servletresponse response) {String content = Request.getparameter ("record_content"); PrintWriter Printwriter=null; Diskfileitemfactory diskfileitemfactory = new Diskfileitemfactory ();//Instantiate a file factory//Build a File upload class Servletfileupload Servletfileupload = new Servletfileupload (diskfileitemfactory);// Generates a Servlet object that handles file uploads Servletfileupload.setfilesizemax (3 * 1024x768 * 1024x768); Servletfileupload.setsizemax (6 * 1024 * 1024);// Upload file Total size try {//parse request and get upload file of Fileitem object 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);//data stored in database System.out.println (" ********************** "+ Newfile.getpath ()); Mfileinfodao.addfilepathinfos (Newfile.getpath (), content);p Rintwriter.write ("Data submitted successfully! "); 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);//data stored in database Mfileinfodao.addfilepathinfos (Newfile.getpath (), content); Printwriter.write ("Data submitted successfully! "); 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 Blocke.printstacktrace ();} catch (Exception e) {//Todo auto-g Enerated catch Blocke.printstacktrace ();}}



3. Database Design Code:

(1) Database operation interface Definition

Public interface Fileinfodao {/** * Add file path to database * @param filePath file path * @param content recording details */public void Addfilepathinf OS (string filepath,string content);/** * Delete path information for a recording * @param details of the content recording */public void Deleteafilepathinfo (string con tent);/** * Delete all audio file paths */public void Deleteallfilepathinfos ();/** * Query all file paths * @return */public list<map<string,s Tring>> getallfilepaths ();}

(2) Database Operation implementation Class

public class Fileinfodaoimpl implements Fileinfodao {//Indicates the user name that defines the database private final String USERNAME = "root";//defines the password for the database Priva Te final String PASSWORD = "admin";//define driver information for the database private final static string DRIVER = "Com.mysql.jdbc.Driver";//define Database connection pri vate Static Connection mconnection;//defines the address of the Access database private final String URL = "Jdbc:mysql://192.168.1.109:3306/fileinfos" ;//define the execution object of the SQL statement private PreparedStatement pstmt;//Define the result collection returned by the query private ResultSet resultset;public Fileinfodaoimpl () {// Load driver try {class.forname (DRIVER);} catch (ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ( );}} @Overridepublic void Addfilepathinfos (String filePath, string content) {PreparedStatement PreparedStatement = null;try { Get database Connection mconnection = Drivermanager.getconnection (URL, "root", "admin"),//Get SQL statement execution Object preparedstatement = Mconnection.preparestatement ("INSERT into filepaths (file_path,record_content) VALUES (?,?)"); /Set parameter preparedstatement.setstring (1, FilePath);p reparedstatement.setstring (2, content);//Execute SQL Statement preparedstatement.execute ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {if (PreparedStatement! = null) {T ry {preparedstatement.close ();p reparedstatement = null;} catch (SQLException e) {//TODO auto-generated catch Blocke.prin Tstacktrace ();}} if (mconnection! = null) {try {mconnection.close (); mconnection = null;} catch (SQLException e) {//TODO auto-generated Cat CH Blocke.printstacktrace ();}}} @Overridepublic void Deleteafilepathinfo (String content) {preparedstatement preparedstatement=null;//get database connection try { Mconnection=drivermanager.getconnection (URL, "root", "admin");//Get SQL statement execution Object preparedstatement= Mconnection.preparestatement ("Delete from filepaths where record_content=?"); /Set parameter preparedstatement.setstring (1, content);p Reparedstatement.execute ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Finally{if (preparedstatement!=null) {try {preparedstatement.close ();p reparedstatement=null;} catch(SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (mconnection!=null) {try {mconnection.close (); mconnection=null;} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} @Overridepublic void Deleteallfilepathinfos () {PreparedStatement Preparedstatement=null;try {mconnection= Drivermanager.getconnection (URL, Username,password);p reparedstatement=mconnection.preparestatement ("Delete from Filepaths ");p Reparedstatement.execute ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Finally{if (preparedstatement!=null) {try {preparedstatement.close ();p reparedstatement=null;} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (mconnection!=null) {try {mconnection.close (); mconnection=null;} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} @Overridepublic 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");//Query 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 Blocke.printstacktrace ();} Finally{if (preparedstatement!=null) {try {preparedstatement.close ();p reparedstatement=null;} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (mconnection!=null) {try {mconnection.close (); mconnection=null;} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} return results;}}

(3) Static factory method of database operation object (singleton mode)

public class Filepathinfosdaofactory {private static Fileinfodao mfileinfodaoimpl;/** * Get database Operations Singleton Object *  * @return */pub Lic static Fileinfodao Getinstanse () {if (Mfileinfodaoimpl = = null) {Mfileinfodaoimpl = new Fileinfodaoimpl ();} return Mfileinfodaoimpl;}}



The Android client uploads the SD card file to the server side and saves it in the PC hard drive folder

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.