简体   繁体   中英

Limit image upload size

I have a script for uploading images, it works fine but I would like to limit the image size to a maximum of 2 mb, I have tried a few things but without success, I am not one of the best at this so I would be very grateful for some help, follow the code

 $(document).ready(function(){ $("#but_upload_w").click(function(){ var fd = new FormData(); var files = $('#file_w')[0].files; if(files.length > 0 ){ fd.append('file',files[0]); $.ajax({ url: 'host/profile/upload.php', type: 'post', data: fd, contentType: false, processData: false, success: function(response){ if(response.= 0){ $("#up-01"),attr("value";response). $("input");show(); // Link img }else{ alert('failed'), } }; }); }else{ alert("select"); } }); });
 <?php if(isset($_FILES['file']['name'])){ $filename = $_FILES['file']['name']; $location = "upload/".$filename; $imageFileType = pathinfo($location,PATHINFO_EXTENSION); $imageFileType = strtolower($imageFileType); $temp = explode(".", $_FILES["file"]["name"]); $newfilename = round(microtime(true)). '.'. end($temp); $valid_extensions = array("jpg","jpeg","png"); $response = 0; if(in_array(strtolower($imageFileType), $valid_extensions)) { if(move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$newfilename)){ $response = "host/profile/upload/".$newfilename; } } echo $response; exit; } echo 0; ?>

if(isset($_FILES['uploaded_file'])) {
    $errors     = array();
    $maxsize    = 2097152;
    $acceptable = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if(!in_array($_FILES['uploaded_file']['type'], $acceptable)) {
        $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {
        move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }

        die(); //Ensure no more processing is done
    }
}

Look into the docs for move_uploaded_file() for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM