0

我正在开发一个应用程序,我正在使用下面的代码将文件上传到 .net 服务器。

public class HttpFileUpload implements Runnable{

    URL connectURL;
    String responseString;
    String Title;
    String Description;
    byte[ ] dataToServer;
    FileInputStream fileInputStream = null;

    public HttpFileUpload(String urlString, String vTitle, String vDesc){
        try{
                connectURL = new URL(urlString);
                Title= vTitle;
                Description = vDesc;
        }catch(Exception ex){
            Log.i("HttpFileUpload","URL Malformatted");
        }
    }    
    public void Send_Now(FileInputStream fStream){
            fileInputStream = fStream;
            Sending();
}



    void Sending(){
    //    String iFileName = "ovicam_temp_vid.mp4";
        String iFileName = CONST.USER_NAME+".db";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag="fSnd";
        try
        {
                Log.i(Tag,"Starting Http File Sending to URL");

                // Open a HTTP connection to the URL
                HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod("POST");

                conn.setRequestProperty("Connection", "Keep-Alive");

                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

                conn.setRequestProperty("FILE_NAME", ""+CONST.USER_NAME+".db");

                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(Title);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);

                dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(Description);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);

                dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
                dos.writeBytes(lineEnd);

                Log.i(Tag,"Headers are written");

                // create a buffer of maximum size
                int bytesAvailable = fileInputStream.available();

                int maxBufferSize = 1024;
                int bufferSize = Math.min(bytesAvailable, maxBufferSize);
                byte[ ] buffer = new byte[bufferSize];

                // read file and write it into form...
                int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0)
                {
                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable,maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0,bufferSize);
                }
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // close streams
                fileInputStream.close();

                dos.flush();

                Log.i(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

                InputStream is = conn.getInputStream();

                // retrieve the response from server
                int ch;

                StringBuffer b =new StringBuffer();
                while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
                String s=b.toString();
                Log.i("Response",s);
                dos.close();
        }
        catch (MalformedURLException ex)
        {
                Log.i(Tag, "URL error: " + ex.getMessage(), ex);
        }

        catch (IOException ioe)
        {
                Log.i(Tag, "IO error: " + ioe.getMessage(), ioe);
        }
}


    @Override
    public void run() {
        // TODO Auto-generated method stub

    }

}

在这里我称之为:

public void UploadFile(String path) throws IOException{
         try {
             // Set your file path here
         //    FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().toString()+"/DCIM/file.mp4");
             Log.i("Upload file path: ",path);
             FileInputStream fstrm = new FileInputStream(path);
               Log.i("FileInputStream", ""+fstrm);

             // Set your server page url (and the file title/description)

               HttpFileUpload hfu = new HttpFileUpload("http://192.168.1.112/abc/", "ZoneSoft","Database file");

             hfu.Send_Now(fstrm);

           } catch (FileNotFoundException e) {
             // Error: File not found
               Log.e("FileNotFoundException: ", e.getMessage());
           }
         }




   try {
                            String selectedFilePath = Environment.getExternalStorageDirectory().getPath()+"/"+CONST.USER_NAME+".db";
                            Log.i("selectedFilePath: ", selectedFilePath);
                            UploadFile(selectedFilePath);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

我只想问是否需要在服务器端编码来处理我发送的文件?

4

2 回答 2

0

尝试这样的事情

InputStream is = new FileInputStream("DB path"); 
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
   bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
byte[] dataToSend = Base64.encode(bytes, Base64.DEFAULT);
....... //webservice to go///

然后将dataToSend其从android发送到服务。这个数组必须保存在.net中可能是这样的。或者您可以读取该字节 [] 并将其转换为相关的文件格式

于 2013-11-15T06:50:56.490 回答
0

最后,我找到了与将 .db 文件上传到服务器相关的上述问题的解决方案:

以下是上传文件的步骤:

1.) new AsynUpload().execute();
2.) class AsynUpload extends AsyncTask<Void,Integer,String>
{
String result="";
ProgressDialog dialog=null;
String iFileName = CONST.USER_NAME+".db";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";

@Override
protected void onPreExecute()
{
Log.i("AsynUpload is callinmg...", "calling");
dialog=new ProgressDialog(Upload_Database.this);
dialog.setMessage("File uploading...");
dialog.setCancelable(false);
dialog.show();
}

@Override
protected String doInBackground(Void... params) {
try 
{
UTILITIES.copyDBToSDCard();
String selectedFilePath = "/data/data/com.DxS.androidSunTec.visioapp/databases/"+CONST.USER_NAME+".db";
FileInputStream fstrm = new FileInputStream(selectedFilePath);
URL connectURL = new URL(CUSTOM_URL.UPLOAD_URL+"Default.aspx");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
conn.setRequestProperty("FILE_NAME", ""+CONST.USER_NAME+".db");
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(""+CONST.USER_NAME);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);                    
dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(loc_code+"~"+user_code+"~"+fyid);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);

// create a buffer of maximum size
int bytesAvailable = fstrm.available();

int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];

// read file and write it into form...
int bytesRead = fstrm.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
    dos.write(buffer, 0, bufferSize);
    bytesAvailable = fstrm.available();
    bufferSize = Math.min(bytesAvailable,maxBufferSize);
    bytesRead = fstrm.read(buffer, 0,bufferSize);
    }
    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // close streams
    fstrm.close();
    // 103424
    dos.flush();
    InputStream is = conn.getInputStream();

    // retrieve the response from server
    int ch;

    StringBuffer b =new StringBuffer();
    while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
    String s=b.toString();
    Log.i("Response",s);
    dos.close();

    result="OK";
    }

    catch (MalformedURLException ex)
    {
    result = "MalformedURLException";
    Log.i(Tag, "URL error: " + ex.getMessage(), ex);
    }
    catch (IOException ioe)
    {
    result = "IOException";
    Log.i(Tag, "IO error: " + ioe.getMessage(), ioe);
    }
    catch(Exception e)
    {
    Log.e("Exception","Exception"+e.getMessage());
    result="FAILURE";
    }
    finally
    {
    if (result.equalsIgnoreCase("OK"))
    {
    File file = new File("/data/data/com.test.app/databases/"+CONST.USER_NAME+".db");
        if(file.exists())
        {
        file.delete();
        Log.i("uploading database file Deleted from sd card :", "deleted");
        }
    file = new File("/data/data/com.test.app/databases/"+DatabaseHelper.DB_NAME);
        if(file.exists())
        {
        file.delete();
        Log.i("Original database file Deleted from sd card :", "deleted");
        }

        MyActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
            // TODO Auto-generated method stub
            AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
            LayoutInflater inflater = getLayoutInflater();
            View vw = inflater.inflate(R.layout.custom_title, null);
            builder.setCustomTitle(vw);
            builder.setMessage("File uploaded successfully!")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                    finish();
                    }
                });
                    builder.create();
                    builder.show();
                    }
                });
                }
            else
            {
            MyActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
                LayoutInflater inflater = getLayoutInflater();
                View vw = inflater.inflate(R.layout.custom_title, null);
            builder.setCustomTitle(vw);
            builder.setMessage("File uploading failed, please try again!")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                        }
                    });
                        builder.create();
                        builder.show();
                        }
                    });
                    }
                      }
                    return result;
                }   

                 @Override
                 protected void onProgressUpdate(Integer... values)
                 {
                     super.onProgressUpdate(values);
                 // dialog.incrementProgressBy(5);   
                }
                @Override
                protected void onPostExecute(String result)
                {
                    dialog.dismiss();

                    if (result.equalsIgnoreCase("OK"))
                    {
                    }
                    else
                    {
                    }
                }
              }

3.) UTILITIES class:

public static void copyDBToSDCard() {
        try {
            InputStream myInput = new FileInputStream("/data/data/com.DxS.androidSunTec.visioapp/databases/"+DatabaseHelper.DB_NAME);

            Log.i("sd card path: ", ""+Environment.getExternalStorageDirectory().getPath().toString());

        //    File file = new File(Environment.getExternalStorageDirectory().getPath()+"/"+CONST.USER_NAME+".db");
            File file = new File("/data/data/com.DxS.androidSunTec.visioapp/databases/"+CONST.USER_NAME+".db");
            if (!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    Log.i("FO","File creation failed for " + file);
                }
            }

       //     OutputStream myOutput = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+CONST.USER_NAME+".db");
            OutputStream myOutput = new FileOutputStream("/data/data/com.DxS.androidSunTec.visioapp/databases/"+CONST.USER_NAME+".db");

            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer))>0){
                myOutput.write(buffer, 0, length);
            }

            //Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
            Log.i("FO","copied");

        } catch (Exception e) {
            Log.i("FO","exception="+e);
        }

}

于 2014-01-06T06:23:15.653 回答