将图像文件从Android应用程序发送到服务器

时间:2017-03-02 14:58:48

标签: java android upload httpurlconnection

我使用this代码段编写了一个AsyncTask类,用于将图像发送到服务器。这是doInBackground方法中的一部分代码,负责发送图像和一些参数:

    String fileName = params[3];

    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(fileName);

    if (!sourceFile.isFile()) {

        Log.e("debug", "Source File not exist: " + fileName);


    } else {
        try {
            /////////////////////////////////////////////////////////////////////////////
            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(params[0]);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            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("pic", fileName);

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

            //here I add some additional data
            addFormField(dos,"idapp", params[1]);
            addFormField(dos,"idlesson", params[2]);
            addFormField(dos,"ip", params[4]);

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

            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            String byteArray = "";
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                byteArray += buffer.toString();
                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)
            int serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("debug", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            BufferedInputStream in;
            try {
                in = new BufferedInputStream(conn.getInputStream());
            } catch (IOException e) {
                String err = (e.getMessage() == null) ? "IOException in creating BufferedInputStream" : e.getMessage();
                Log.e("debug", err);
                return err;
            }

            try {
                resultToDisplay = IOUtils.toString(in, "UTF-8");
                //to [convert][1] byte stream to a string
            } catch (IOException e) {
                Log.e("debug", e.getMessage());
            }

            Log.i("debug", "result: " + resultToDisplay);
            //close the streams //
            //////////////////////////////////////
            fileInputStream.close();
            dos.flush();
            dos.close();
            //////////////////////////////////////
        } catch (MalformedURLException ex) {

            Log.e("debug", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {
            Log.e("debug", "error: " + e.getMessage(), e);
        }

    } // End else block
    return resultToDisplay;

以下是我如何调用它:

        CallAPI c = new CallAPI();
        c.execute(CallAPI.uploadURL, getResources().getString(R.string.appID), currentLessonID+"", pathToTempFile, CallAPI.IP);

问题在于,根据服务器的响应,它根本没有收到任何图像。这是代码的一部分,负责我目前收到的答案:

if(!isset($_FILES['pic'])) ex_fail("pic not set");
if($_FILES['pic']['error'] != 0) ex_fail("pic upload error ");

我得到" pic未设置"错误。虽然根据日志,我实际上将图像写入DataOutputStream,我比较了字节数 - 它是相同的。

什么可能导致问题?

0 个答案:

没有答案