简体   繁体   English

android上传图片文件到PHP服务器

[英]android upload image file into PHP server

I took this code on Internet.我在互联网上拿了这个代码。 I can upload image file to Server successful.我可以成功上传图像文件到服务器。 However, the image files cannot be opened.但是,无法打开图像文件。 I think the content of the files has problem after uploading.我认为上传后文件的内容有问题。 Can anybody help me please?有人可以帮我吗? Thank you very much非常感谢

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

And the bellow is my code in PHP:下面是我在 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