将文件上传到服务器不工作

时间:2017-05-16 12:32:49

标签: java php android httpurlconnection

  

我的代码如下。

     

上传后(不同文件大小的时间不同)我得到了200 Ok和回复

public class CloudFileUploader extends AsyncTask<String, Void, String> {



@Override
protected String doInBackground(String... params) {

    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;
    int serverResponseCode = 0;
    try {
        FileInputStream fileInputStream = new FileInputStream(mFile);
        URL url = new URL(CloudConstants.getFileUploadBaseUrl());
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary + ";key=fileToUpload");
        conn.setRequestProperty("Accept", "application/json");
        String contentLength=Long.toString(mFile.length());
 //            conn.setRequestProperty("Content-Length",contentLength );

        AppSharedPreference mPref = new AppSharedPreference(mContext);
        String token = mPref.getStringPrefValue(PreferenceConstants.USER_TOKEN);
        conn.setRequestProperty("token", token);
        conn.setRequestProperty("groupId", "" + mMessage.getReceiverId());
        conn.setRequestProperty("message", "" + mMessage.getMessageBody());
        conn.setRequestProperty("messageType", "" + mMessage.getMessageType());
        conn.setRequestProperty("senderName", "" + mMessage.getSenderName());

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

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

        bytesAvailable = fileInputStream.available();
        Log.i(TAG, "Initial .available : " + bytesAvailable);

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

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

        serverResponseCode = conn.getResponseCode();
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException | FileNotFoundException | ProtocolException ex) {
        ex.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (serverResponseCode == 200) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                    .getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            if (onFileUploadListener != null) {
                onFileUploadListener.onUploadFailed(mMessage, new AppError(ErrorHandler.ERROR_FROM_SERVER, ErrorHandler.ErrorMessage.ERROR_FROM_SERVER));
            }
        }
        return sb.toString();
    } else {
        return "Could not upload";
    }
}
}

我放了conn.setRequestProperty("Content-Length",contentLength );但它会抛出java.net.ProtocolException。

我测试了不同的代码,但问题仍然存在。

  

下面给出的是我的php服务器脚本。

$status['apiId'] = _GROUP_FILE_UPLOAD_API;
    $user_id = $this->user['user_id'];
    $target_dir = ROOTDIR_PATH . DS . "data" . DS . "GroupFileUploads" . DS;
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
     $fileUpload = NULL;
    if ($this->headers->get('groupId')) {
        $fileUpload['groupId'] = $groupId = $this->headers->get('groupId')->getFieldValue();
    }
    if ($this->headers->get('messageType')) {
        $fileUpload['messageType'] = $messageType = $this->headers->get('messageType')->getFieldValue();
    } if ($this->headers->get('message')) {
        $fileUpload['message'] = $message = $this->headers->get('message')->getFieldValue();
    }
    if ($this->headers->get('senderName')) {
        $fileUpload['senderName'] = $senderName = $this->headers->get('senderName')->getFieldValue();
    }

代码无效。它没有保存我给的文件夹。

  

但它是从 Postman AdvancedRestClient

开始的      

当我把die()然后我得到了

Array( [myFile] => Array ( [name] => 1495018448FaceApp_1494992050886.jpg [type] => [tmp_name] => /tmp/phpH2kH47 [error] => 0 [size] => 917953 ))

[type] =>应该是image/jpg,但它是空的

0 个答案:

没有答案