簡體   English   中英

android上傳圖片文件到PHP服務器

[英]android upload image file into PHP server

我在互聯網上拿了這個代碼。 我可以成功上傳圖像文件到服務器。 但是,無法打開圖像文件。 我認為上傳后文件的內容有問題。 有人可以幫我嗎? 非常感謝

public static void put(String targetURL, File file, String username, String password) throws Exception {

    String BOUNDRY = "==================================";
    HttpURLConnection conn = null;

    try {

        // Make a connect to the server
        URL url = new URL(targetURL);
        conn = (HttpURLConnection) url.openConnection();


        if (username != null) {
            String usernamePassword = username + ":" + password;
            //String encodedUsernamePassword = Base64.encodeBytes(usernamePassword.getBytes());
            String encodedUsernamePassword = String.valueOf(Base64.encodeBase64(usernamePassword.getBytes()));
            conn.setRequestProperty ("Authorization", "Basic " + encodedUsernamePassword);
        }


        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);


        DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
        dataOS.writeBytes("--");
        dataOS.writeBytes(BOUNDRY);
        dataOS.writeBytes("\n");
        dataOS.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\"; fileName=\"" + file.getName() +"\"" + "\n");
        dataOS.writeBytes("\n");
        dataOS.writeBytes(new String(getBytesFromFile(file)));
        dataOS.writeBytes("\n");
        dataOS.writeBytes("--");
        dataOS.writeBytes(BOUNDRY);
        dataOS.writeBytes("--");
        dataOS.writeBytes("\n");
        dataOS.flush();
        dataOS.close();




        int responseCode = conn.getResponseCode();
        if (responseCode != 200) {
            throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url));
        }

        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[4096];
        int bytesRead;
        while((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();

        is.close();
        String response = new String(bytesReceived);

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

}

public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
            && (numRead = is.read(bytes, offset, Math.min(bytes.length - offset, 512*1024))) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}

下面是我在 PHP 中的代碼:

$target = "/upload/";
$target = $target . basename( $_FILES['fileToUpload']['name']) ; 



if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target)) {
    echo "The file ". basename( $_FILES['fileToUpload']['name']). " has been uploaded";
    $result['login'] = true;
}else {
    $result['login']=false;
    echo "Sorry, there was a problem uploading your file.";
 }

$json = json_encode($result, JSON_PRETTY_PRINT);
print_r($json);

設置Content-Type時可能會出現問題,請嘗試將其刪除

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM