Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tải lên file (upload) lên website bằng Form HTML?

Để cho phép người dùng tải file lên website, sử dụng ô tải file (file upload box / file select box). Tạo bằng thẻ <input> với type="file".

Ví dụ

<!DOCTYPE html>
<html>
<head>
    <title>Tải lên file</title>
</head>
<body>
    <form action="/upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="upload" accept="image/*" />
        <br><br>
        <input type="submit" value="Tải lên">
    </form>
</body>
</html>

Các thuộc tính quan trọng:

Thuộc tínhMô tả
nameTên control, dùng để nhận diện giá trị ở server.
acceptLoại file cho phép (VD: image/*, .pdf, image/png, image/jpeg).
multipleCho phép chọn nhiều file cùng lúc.
requiredBắt buộc chọn file.
captureTrên mobile: camera, microphone, camcorder.

Lưu ý quan trọng:

  • Form bắt buộc có enctype="multipart/form-data" khi upload file.
  • method="post" (không dùng GET cho upload file).
  • Server-side (PHP, Node.js, Python...) cần xử lý multipart form data (dùng multer, busboy, $_FILES...).
  • Validate loại file, kích thước ở cả client và server (bảo mật).