--------------- <> -----------------
--- KHOA HỌC - CÔNG NGHỆ - GIÁO DỤC - VIỆC LÀM ---
--- Học để đi cùng bà con trên thế giới ---

Tìm kiếm trong Blog

Hiển thị các bài đăng có nhãn upload tập tin. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn upload tập tin. Hiển thị tất cả bài đăng

Ngu ngơ học làm web (83) - Upload tập tin

Tiếp theo của: Ngu ngơ học làm web (82) - Kỹ thuật đệ quy 2
-----

Phần 83.       Upload tập tin


Đây là clip số 93:


Để tải một tập tin từ máy người dùng lên server (upload) cần thực hiện các bước sau:

- Chuẩn bị tập tin để tải lên

- Tạo một form bằng HTML, thẻ <form> phải có thuộc tính [enctype=“multipart/form-data”]

- Form phải có một input với [type=“file”][name=“fileUpload”]

- Sau khi bấm nút Submit, sẽ kiểm tra biến $_FILE[‘fileUpload’] trên server để có được các thông tin của tập tin đã được tải lên

- Sau khi bấm nút Submit, phần nội dung của tập tin cũng được gửi lên server

- Tại server:

+ Tập tin được lưu vào bộ nhớ tạm, với tên là *.tmp

+ Di chuyển tập tin tạm vào thư mục mong muốn

+ Đổi tên tập tin tạm thành tên mới như mong muốn

Các thông tin có trong biến $_FILE[‘fileUpload’]:

- $_FILE[‘fileUpload’][‘name’]: tên ban đầu của tập tin được tải lên server

- $_FILE[‘fileUpload’][‘size’]: kích thước của tập tin

- $_FILE[‘fileUpload’][‘type’]: kiểu của tập tin

- $_FILE[‘fileUpload’][‘tmp_name’]: tên tập tin tạm, chứa nội dung của tập tin được tải lên server (tuy nhiên sau khi submit, tìm kiếm thử tập tin này trên server thì không thấy, lý do: tập tin này bị xóa ngay khi đoạn mã về upload tập tin thực hiện xong?).

- $_FILE[‘fileUpload’][‘error’]: thông báo lỗi khi tải tập tin

Đoạn mã ví dụ:

[index.php]

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>PHP</title>
</head>
<body>
<?php
  if (isset($_FILES['fileUpload'])) {
    $fileUpload = $_FILES['fileUpload'];
    if ($fileUpload['name'] != null) {
      $fileNameTmp = $fileUpload['tmp_name'];
      $destination = './files/' . $fileUpload['name'];
      if (move_uploaded_file($fileNameTmp, $destination)) {
        echo 'upload succeeded!';
      } else {
        echo 'upload failed!';
      }
    }
  }
 
?>
  <form action="#" method="post" enctype="multipart/form-data">
    <input type="file" name="fileUpload">
    <input type="submit" value="Submit">
  </form>
</body>
</html>

Thực hiện upload tập tin với tên mới để tránh tình trạng ghi đè.

[index.php]

Sửa lại đoạn mã như sau:

  // tạo tên tập tin ngẫu nhiên
  function randomString($length = 5) {
    // tạo ra một mảng gồm các kí tự AZaz09
    $arrChar = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9'));
    // chuyển mảng thành chuỗi
    $chars = implode($arrChar, '');
    // đảo chuỗi ngẫu nhiên
    $chars = str_shuffle($chars);
    $result = substr($chars, 0, 5);
    return $result;
  }

  if (isset($_FILES['fileUpload'])) {
    $fileUpload = $_FILES['fileUpload'];
    if ($fileUpload['name'] != null) {
      $fileNameTmp = $fileUpload['tmp_name'];
      $random = randomString(5);
      $destination = './files/' . $random . '_' . $fileUpload['name'];
      if (move_uploaded_file($fileNameTmp, $destination)) {
        echo 'upload succeeded!';
      } else {
        echo 'upload failed!';
      }
    }

  }
-----------
Cập nhật [16/9/2020]
-----------
Xem thêm:

Ngu ngơ học làm web (x47) - CakePHP2 - Xóa folder, upload tập tin, upload ảnh

Tiếp theo của: Ngu ngơ học làm web (x46) - CakePHP2 – CKEditor, block, lọc dấu tiếng Việt, folder
-----

Phần x47. CakePHP2 – Xóa folder, upload tập tin, upload ảnh


Xem (clip số 45b – chickenrainshop):

- Xóa thư mục (45b)

- Cập nhật dữ liệu trong mySQL (2":21)

Trong clip có hướng dẫn tạo thêm trường folder trong bảng categories, tuy nhiên để ý thấy nội dung trường folder giống với trường slug, nên không tạo thêm trường folder nữa mà sử dụng luôn trường slug để làm việc.

Đưa câu khai báo sử dụng Folder lên đầu [CategoriesController.php]

<?php
App::uses('AppController', 'Controller');
App::uses('Folder', 'Utility');

Thực hiện xóa một Category, đồng thời xóa luôn thư mục chứa hình ảnh tương ứng:

[CategoriesController.php action admin_delete()]

public function admin_delete($id = null) {
                        $this->Category->id = $id;
                        if (!$this->Category->exists()) {
                                    throw new NotFoundException(__('Invalid category'));
                        }
                        $this->request->allowMethod('post', 'delete');
                        $category = $this->Category->findById($id);
                        $folder = new Folder(APP.'webroot/files/'.$category['Category']['slug']);
                        if ($folder->delete()) {
                                    if ($this->Category->removeFromTree($id, true)) {
                                                $this->Flash->success(__('The category has been deleted.'));
                                    } else {
                                                $this->Flash->error(__('The category could not be deleted. Please, try again.'));
                                    }
                        } else {
                                                $this->Flash->error(__('Không xóa được thư mục. Vui lòng thử lại sau.'));
                                    }
                        return $this->redirect(array('action' => 'index'));
            }

Xem (clip số 46a – chickenrainshop):

- upload ảnh (46a)

- Html->image (1":19)

- Khai báo type='file' trong form  (3":19)

- uploadFile (8":05)

Tải một tập tin ảnh lên server, thực hiện minh họa trên trang ‘edit một cuốn sách’.

Hiển thị ảnh lên view:

[View\Books\admin_edit.ctp]

<?php echo $this->Form->create('Book', ['novalidate' => true, 'type' => 'file']); ?>
            <fieldset>
                        <legend><?php echo __('Edit Book'); ?></legend>
            <?php
                        echo $this->Form->input('id');
                        echo $this->Form->input('category_id');
                        echo $this->Form->input('title');
                        echo $this->Form->input('slug');
                        echo $this->Html->image($this->request->data['Book']['image'], ['width'=>140, 'height' => 180]);
                        echo $this->Form->input('image',['label' => '', 'type' => 'file']);

Viết hàm uploadFile():

Khai báo sử dụng class File ở đầu tập tin BooksController.php:

<?php
App::uses('AppController', 'Controller');
App::uses('File', 'Utility');

[BooksController.php]

public function admin_edit($id = null) {
                        if (!$this->Book->exists($id)) {
                                    throw new NotFoundException(__('Invalid book'));
                        }
                        if ($this->request->is(array('post', 'put'))) {
                                    $this->checkSlug($this->request->data, 'Book', 'title');
                                    $this->loadModel('Category');
                                    $category = $this->Category->findById($this->request->data['Book']['category_id']);
                                    $save = true;
                                    if (!empty($this->request->data['Book']['image']['name'])) {
                                                if ($this->uploadFile($category['Category']['slug'])) {
                                                            $location = '/files/'.$category['Category']['slug'].'/'.$this->request->data['Book']['image']['name'];
                                                            $this->request->data['Book']['image'] = $location;
                                                } else {
                                                            $this->Flash->error(__('Không upload được ảnh, vui lòng thử lại!'));
                                                            $save = false;
                                                }          
                                    } else {
                                                unset($this->request->data['Book']['image']);
                                    }
                                    if ($save) {
                                                if ($this->Book->save($this->request->data)) {
                                                            $this->Flash->success(__('The book has been saved.'));
                                                            return $this->redirect(array('action' => 'index'));
                                                } else {
                                                            $this->Flash->error(__('The book could not be saved. Please, try again.'));
                                                }
                                    }                                  
                        } else {
                                    $options = array('conditions' => array('Book.' . $this->Book->primaryKey => $id));
                                    $this->request->data = $this->Book->find('first', $options);
                        }
                        $categories = $this->Book->Category->find('list');
                        $writers = $this->Book->Writer->find('list');
                        $this->set(compact('categories', 'writers'));

            }
-----------
Cập nhật 28/7/2017
-----------
Xem thêm:
Tổng hợp các bài viết về Ngu ngơ học làm web