如何使用文件上传数据发送到服务器 [英] how to send data with file upload to the server

查看:139
本文介绍了如何使用文件上传数据发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前上传的文件在android系统。现在,我想送一些数据可以说并与文件上传ID。所以,我会处理这个ID在服务器端。这里是我如何上传文件。这code工作完全正常。

下面是code

 公众诠释uploadFile(字符串sourceFileUri,最后弦乐imageName){
    //Toast.makeText(getApplicationContext(),imageName,Toast.LENGTH_LONG).show();
    字符串upLoadServerUri =htt​​p://www.example.com/android/fileupload.php;
    字符串文件名= sourceFileUri;
    //Toast.makeText(getApplicationContext(),sourceFileUri,Toast.LENGTH_LONG).show();
    HttpURLConnection的康恩= NULL;
    DataOutputStream类DOS = NULL;
    字符串lineEnd =\\ r \\ n;
    串twoHyphens = - ;
    字符串边界=*****;
    INT读取动作,方bytesAvailable,缓冲区大小;
    字节[]缓冲区;
    INT MAXBUFFERSIZE = 1 * 1024 * 1024;    文件的资源文件=新的文件(sourceFileUri);
    如果(!sourceFile.isFile()){
        Log.e(一个UploadFile,源文件不存在);
        返回0;
    }    尝试{
        //打开一个URL连接到这个Servlet
        的FileInputStream的FileInputStream =新的FileInputStream(的资源文件);
        网址URL =新的URL(upLoadServerUri);
        康恩=(HttpURLConnection类)url.openConnection(); //打开HTTP连接的URL
        conn.setDoInput(真); //允许输入
        conn.setDoOutput(真); //允许输出
        conn.setUseCaches(假); //不要使用缓存副本
        conn.setRequestMethod(POST);
        conn.setRequestProperty(连接,保持活动);
        conn.setRequestProperty(ENCTYPE,多部分/表单数据);
        conn.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);
        conn.setRequestProperty(uploaded_file,文件名);
        DOS =新的DataOutputStream类(conn.getOutputStream());        dos.writeBytes(twoHyphens +边界+ lineEnd);
        dos.writeBytes(内容处置:表格数据;名称= \\uploaded_file \\;文件名= \\+文件名+\\+ lineEnd);
        dos.writeBytes(lineEnd);        参考bytesAvailable = fileInputStream.available(); //创建最大大小的缓冲区        BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
        缓冲区=新的字节[缓冲区大小]         //读取文件,并将其写入形式...
        读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);        而(读取动作大于0){
             dos.write(缓冲液,0,缓冲区大小);
             参考bytesAvailable = fileInputStream.available();
             BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
             读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);
        }        //发送文件数据后necesssary多部分的表单数据...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);        //服务器的响应(code和消息)
        serverResponse code = conn.getResponse code();
        串serverResponseMessage = conn.getResponseMessage();        Log.i(一个UploadFile,HTTP响应是:+ serverResponseMessage +:+ serverResponse code);
        如果(serverResponse code == 200){
            runOnUiThread(新的Runnable(){
                 公共无效的run(){
                     //tv.setText(\"File上传完成)。
                     如果(FILEDATA(globalUID,imageName)){
                         Toast.makeText(Camera.this,文件上传完成。Toast.LENGTH_SHORT).show();
                     }
                 }
            });
        }
        //关闭流//
        fileInputStream.close();
        dos.flush();
        dos.close();    }赶上(MalformedURLException的前){
        dialog.dismiss();
        ex.printStackTrace();
        Toast.makeText(Camera.thisMalformedURLException的,Toast.LENGTH_SHORT).show();
        Log.e(上传文件到服务器,错误:+ ex.getMessage(),除息);
    }赶上(例外五){
        dialog.dismiss();
        e.printStackTrace();
        Toast.makeText(Camera.this,异常:+ e.getMessage(),Toast.LENGTH_SHORT).show();
        Log.e(上传文件到服务器异常,异常:+ e.getMessage(),E);
    }    dialog.dismiss();
    返回serverResponse code;
}


解决方案

您可以编写查询字符串到输出流。

 的OutputStream OS = conn.getOutputStream();
os.write(yourQueryString.getBytes(withSpecificCharset));

和服务器 PHP 脚本可以读取查询参数如常。

  $参数1 = $ _ POST [参数1];

您可以参考 BalusC 的的社区维基回答的<一个href=\"http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests\">How使用java.net.URLConnection中的火灾和处理HTTP请求?。它与文件上传和查询参数的HTTP POST示例中讨论。

I am currently uploading file in android. Now I want to send some data lets say and ID with that fileupload. So I will deal with this ID on the server side. Here is how I am uploading file. This code works perfectly fine.

Here is the code

public int uploadFile(String sourceFileUri, final String imageName) {
    //Toast.makeText(getApplicationContext(), imageName, Toast.LENGTH_LONG).show();
    String upLoadServerUri = "http://www.example.com/android/fileupload.php";
    String fileName = sourceFileUri;
    //Toast.makeText(getApplicationContext(), sourceFileUri, Toast.LENGTH_LONG).show();
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("uploadFile", "Source File Does not exist");
        return 0;
    }

    try { 
        // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

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

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

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

         // read file and write it into form...
        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);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        if(serverResponseCode == 200){
            runOnUiThread(new Runnable() {
                 public void run() {
                     //tv.setText("File Upload Completed.");
                     if(fileData(globalUID, imageName)) {
                         Toast.makeText(Camera.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                     }
                 }
            });
        }
        //close the streams //
        fileInputStream.close();
        dos.flush();
        dos.close();

    } catch (MalformedURLException ex) {
        dialog.dismiss();
        ex.printStackTrace();
        Toast.makeText(Camera.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        dialog.dismiss();
        e.printStackTrace();
        Toast.makeText(Camera.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
    }

    dialog.dismiss();
    return serverResponseCode;
}

解决方案

You can write query string onto output stream.

OutputStream os = conn.getOutputStream();
os.write( yourQueryString.getBytes( withSpecificCharset ) );

And in the server php script you can read query parameters as usual.

$param1 = $_POST[ "param1" ];

You can refer to BalusC's community wiki answer on How to use java.net.URLConnection to fire and handle HTTP requests?. It discussed with examples on HTTP Post with file upload and query parameters.

这篇关于如何使用文件上传数据发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆