Rectangle 27 165

I know this is a old post but some further explanation might be useful for someone trying to upload multiple files... Here is what you need to do:

  • Input name must be be defined as an array i.e. name="inputName[]"
  • Make sure to look for empty file names and paths, the array might contain empty strings. Use array_filter() before count.
//$files = array_filter($_FILES['upload']['name']); something like that to be used before processing files.
// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);

// Loop through each file
for($i=0; $i<$total; $i++) {
  //Get the temp file path
  $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

  //Make sure we have a filepath
  if ($tmpFilePath != ""){
    //Setup our new file path
    $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];

    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {

      //Handle other code here

    }
  }
}

I'm not sure <input type="file"> allows the attribute multiple - what would the expected outcome be? Browser allowing multiple files to be selected?

@Sven Yes it is supported in HTML5 check out this link , my bad looks like IE doesn't support this tho... Geeze our life would be so much easier if everyone just went by the standards... LOL

@AndyBraham brilliant answer, saved me tons of time :)

multiple
<input name="upload[]" type="file" multiple />

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Multiple file upload in php - Stack Overflow

php file-upload
Rectangle 27 145

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running in the browser) sends the form data to the server, then a script on the server handles the upload. Here's an example using PHP.

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
                url: 'upload.php', // point to server-side PHP script 
                dataType: 'text',  // what to expect back from the PHP script, if anything
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         
                type: 'post',
                success: function(php_script_response){
                    alert(php_script_response); // display response from the PHP script, if any
                }
     });
});

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that runs on the server and directs the file to the uploads directory:

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }

?>

Also, a couple things about the destination directory:

  • Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(

    // this is where the file is temporarily stored on the server when uploaded
    // do not change this
    $_FILES['file']['tmp_name'],

    // this is where you want to put the file and what you want to name it
    // in this case we are putting in a directory called "uploads"
    // and giving it the original filename
    'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(
    $_FILES['file']['tmp_name'],
    'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

hey BloodyKnuckles! thanks, i think this was one big thing, i misunderstood. So i added the php file, and now i am a little closer. The second alert also pops up! but the folder is still empty.

Ah, the form input name "sortpic" is changed to "file" in the form_data.append function. So I changed the PHP script to reflect the new form input name. I also pulled the PHP script response into the ajax success alert to help with debugging.

@partho , the code prop('files')[0] accesses the local file intended for upload to the server. If you need more explanation look up jQuery function "prop" and "html5 file upload".

I resolved this issue.The reason for it was the filesize was too large.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - jQuery AJAX file upload PHP - Stack Overflow

javascript php jquery ajax upload
Rectangle 27 25

Multiple files can be selected and then uploaded using the<input type='file' name='file[]' multiple> The sample php script that does the uploading:

<html>
<title>Upload</title>
<?php
    session_start();
    $target=$_POST['directory'];
        if($target[strlen($target)-1]!='/')
                $target=$target.'/';
            $count=0;
            foreach ($_FILES['file']['name'] as $filename) 
            {
                $temp=$target;
                $tmp=$_FILES['file']['tmp_name'][$count];
                $count=$count + 1;
                $temp=$temp.basename($filename);
                move_uploaded_file($tmp,$temp);
                $temp='';
                $tmp='';
            }
    header("location:../../views/upload.php");
?>
</html>

The selected files are received as an array with

$_FILES['file']['name'][0]
$_FILES['file']['name'][1]

Multiple file upload in php - Stack Overflow

php file-upload
Rectangle 27 25

Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:

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)) && (!empty($_FILES["uploaded_file"]["type"]))) {
        $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() (it's called move not store) for more.

Your code is much cleaner; however, I discovered that my issue was actually with the limit set in php5.ini. I am using GoDaddy, which defaults the limit to 2MB. For all files uploaded that are larger than this, the return value of $_FILES['uploaded_file']['size'] comes back as "0" and the return value of $_FILES['uploaded_file']['type'] is empty. I had to modify your code a bit.

hi, I think if(count($errors) !== 0) should be if(count($errors) == 0), though it is not a logical mistake, kind of typo error, but I think it should be corrected to avoid any confusion.

@Dharmang You are correct! I've edited the typo. Thanks. ;)

type
$whitelist = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'txt', 'rtf', 'odt'];$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); if (in_array($extension,$whitelist)){ /* do your stuff */}

@PhpMyCoder What if i upload a file, which is larger than upload_max_filesize in php.ini? No errors were shown in that case. file is also not uploaded.

How to limit file upload type file size in PHP? - Stack Overflow

php file file-upload
Rectangle 27 1135

Phew, Django documentation really does not have good example about this. I spent over 2 hours to dig up all the pieces to understand how this works. With that knowledge I implemented a project that makes possible to upload files and show them as list. To download source for the project, visit https://github.com/axelpale/minimal-django-file-upload-example or clone it:

> git clone https://github.com/axelpale/minimal-django-file-upload-example.git

Update 2013-01-30: The source at GitHub has also implementation for Django 1.4 in addition to 1.3. Even though there is few changes the following tutorial is also useful for 1.4.

Update 2013-05-10: Implementation for Django 1.5 at GitHub. Minor changes in redirection in urls.py and usage of url template tag in list.html. Thanks to hubert3 for the effort.

A basic Django 1.3 project with single app and media/ directory for uploads.

minimal-django-file-upload-example/
    src/
        myproject/
            database/
                sqlite.db
            media/
            myapp/
                templates/
                    myapp/
                        list.html
                forms.py
                models.py
                urls.py
                views.py
            __init__.py
            manage.py
            settings.py
            urls.py

To upload and serve files, you need to specify where Django stores uploaded files and from what URL Django serves them. MEDIA_ROOT and MEDIA_URL are in settings.py by default but they are empty. See the first lines in Django Managing Files for details. Remember also set the database and add myapp to INSTALLED_APPS

...
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'database.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
...
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
...
INSTALLED_APPS = (
    ...
    'myapp',
)

Next you need a model with a FileField. This particular field stores files e.g. to media/documents/2011/12/24/ based on current date and MEDIA_ROOT. See FileField reference.

To handle upload nicely, you need a form. This form has only one field but that is enough. See Form FileField reference for details.

A view where all the magic happens. Pay attention how request.FILES are handled. For me, it was really hard to spot the fact that request.FILES['docfile'] can be saved to models.FileField just like that. The model's save() handles the storing of the file to the filesystem automatically.

Django does not serve MEDIA_ROOT by default. That would be dangerous in production environment. But in development stage, we could cut short. Pay attention to the last line. That line enables Django to serve files from MEDIA_URL. This works only in developement stage.

To make the view accessible, you must specify urls for it. Nothing special here.

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

urlpatterns = patterns('myapp.views',
    url(r'^list/$', 'list', name='list'),
)

The last part: template for the list and the upload form below it. The form must have enctype-attribute set to "multipart/form-data" and method set to "post" to make upload to Django possible. See File Uploads documentation for details.

The FileField has many attributes that can be used in templates. E.g. {{ document.docfile.url }} and {{ document.docfile.name }} as in the template. See more about these in Using files in models article and The File object documentation.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Minimal Django File Upload Example</title>   
    </head>
    <body>
    <!-- List of uploaded documents -->
    {% if documents %}
        <ul>
        {% for document in documents %}
            <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No documents.</p>
    {% endif %}

        <!-- Upload form. Note enctype attribute! -->
        <form action="{% url 'list' %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <p>{{ form.non_field_errors }}</p>
            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
            <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
            </p>
            <p><input type="submit" value="Upload" /></p>
        </form>
    </body>
</html>
> cd myproject
> python manage.py syncdb
> python manage.py runserver

Finally, everything is ready. On default Django developement environment the list of uploaded documents can be seen at localhost:8000/list/. Today the files are uploaded to /path/to/myproject/media/documents/2011/12/17/ and can be opened from the list.

I hope this answer will help someone as much as it would have helped me.

Found the location in django docs that shows file uploads. The example in this answer is excellent, but the info in the django docs will be kept up to date with new releases. docs.djangoproject.com/en/dev/topics/http/file-uploads

The example doesn't work for Django "1.5". In the HTML {% url list %} becomes {% url "list" %}.

@AkseliPaln could you also include a example for django admin in your example

Thank you very much . It really works for me. However, for the upcoming viewers, you should check the code in gitHub for the best compatibility with new versions of Python and Django. For example, the the views.py, render_to_response() should be replaced with render(request,...,) to avoid the CSRF error. Cheers.

Need a minimal Django file upload example - Stack Overflow

django file upload
Rectangle 27 1136

Phew, Django documentation really does not have good example about this. I spent over 2 hours to dig up all the pieces to understand how this works. With that knowledge I implemented a project that makes possible to upload files and show them as list. To download source for the project, visit https://github.com/axelpale/minimal-django-file-upload-example or clone it:

> git clone https://github.com/axelpale/minimal-django-file-upload-example.git

Update 2013-01-30: The source at GitHub has also implementation for Django 1.4 in addition to 1.3. Even though there is few changes the following tutorial is also useful for 1.4.

Update 2013-05-10: Implementation for Django 1.5 at GitHub. Minor changes in redirection in urls.py and usage of url template tag in list.html. Thanks to hubert3 for the effort.

A basic Django 1.3 project with single app and media/ directory for uploads.

minimal-django-file-upload-example/
    src/
        myproject/
            database/
                sqlite.db
            media/
            myapp/
                templates/
                    myapp/
                        list.html
                forms.py
                models.py
                urls.py
                views.py
            __init__.py
            manage.py
            settings.py
            urls.py

To upload and serve files, you need to specify where Django stores uploaded files and from what URL Django serves them. MEDIA_ROOT and MEDIA_URL are in settings.py by default but they are empty. See the first lines in Django Managing Files for details. Remember also set the database and add myapp to INSTALLED_APPS

...
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'database.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
...
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
...
INSTALLED_APPS = (
    ...
    'myapp',
)

Next you need a model with a FileField. This particular field stores files e.g. to media/documents/2011/12/24/ based on current date and MEDIA_ROOT. See FileField reference.

To handle upload nicely, you need a form. This form has only one field but that is enough. See Form FileField reference for details.

A view where all the magic happens. Pay attention how request.FILES are handled. For me, it was really hard to spot the fact that request.FILES['docfile'] can be saved to models.FileField just like that. The model's save() handles the storing of the file to the filesystem automatically.

Django does not serve MEDIA_ROOT by default. That would be dangerous in production environment. But in development stage, we could cut short. Pay attention to the last line. That line enables Django to serve files from MEDIA_URL. This works only in developement stage.

To make the view accessible, you must specify urls for it. Nothing special here.

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

urlpatterns = patterns('myapp.views',
    url(r'^list/$', 'list', name='list'),
)

The last part: template for the list and the upload form below it. The form must have enctype-attribute set to "multipart/form-data" and method set to "post" to make upload to Django possible. See File Uploads documentation for details.

The FileField has many attributes that can be used in templates. E.g. {{ document.docfile.url }} and {{ document.docfile.name }} as in the template. See more about these in Using files in models article and The File object documentation.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Minimal Django File Upload Example</title>   
    </head>
    <body>
    <!-- List of uploaded documents -->
    {% if documents %}
        <ul>
        {% for document in documents %}
            <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No documents.</p>
    {% endif %}

        <!-- Upload form. Note enctype attribute! -->
        <form action="{% url 'list' %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <p>{{ form.non_field_errors }}</p>
            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
            <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
            </p>
            <p><input type="submit" value="Upload" /></p>
        </form>
    </body>
</html>
> cd myproject
> python manage.py syncdb
> python manage.py runserver

Finally, everything is ready. On default Django developement environment the list of uploaded documents can be seen at localhost:8000/list/. Today the files are uploaded to /path/to/myproject/media/documents/2011/12/17/ and can be opened from the list.

I hope this answer will help someone as much as it would have helped me.

Found the location in django docs that shows file uploads. The example in this answer is excellent, but the info in the django docs will be kept up to date with new releases. docs.djangoproject.com/en/dev/topics/http/file-uploads

The example doesn't work for Django "1.5". In the HTML {% url list %} becomes {% url "list" %}.

@AkseliPaln could you also include a example for django admin in your example

Thank you very much . It really works for me. However, for the upcoming viewers, you should check the code in gitHub for the best compatibility with new versions of Python and Django. For example, the the views.py, render_to_response() should be replaced with render(request,...,) to avoid the CSRF error. Cheers.

Need a minimal Django file upload example - Stack Overflow

django file upload
Rectangle 27 5

File could not be Attached from client PC (upload)

In the HTML form I have not added following line, so no attachment was going:

After adding above line in form (as below), the attachment went perfect.

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

Send File Attachment from Form Using phpMailer and PHP - Stack Overflo...

php file-upload phpmailer email-attachments
Rectangle 27 121

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 121

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 121

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 121

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 6

Check whether you have permissions in that folder (C:/inetpub/wwwroot/PHP_Ramp/upload/) to write file. You can check the folder by right clicking and selecting properties -> Security

I appended the following to the beginning of my code: mkdir("C:/inetpub/wwwroot/PHP_Ramp/upload/", 0766); and I'm still getting "move failed".

He means to make sure that the folder itself is writable by the PHP script. Adding 0766 is just modifying the moved file's permission once it's written.

The mode argument is ignored in Windows per us.php.net/manual/en/function.mkdir.php - I think @Shyju means NTFS permissions since @Mik said he's using IIS7.

sudo chmod -R a+w directoryhere

PHP File Upload / move_uploaded_file Not Working - Stack Overflow

php file file-upload upload
Rectangle 27 38

I think this is because of a typo. Instead of

upload_max_filesize = 7MB
upload_max_filesize = 7M

use phpinfo() again to check what value actually gets applied.

You'r right, that solved the problem. The trick I didn't realize was that phpinfo() does show 7MB value, but it doesn't consider it appropriate. it's all good now, luv ya

php - $_FILE upload large file gives error 1 even though upload_max_si...

php file upload size
Rectangle 27 89

Using if( $ext !== 'gif') might not be efficient what if you allow like 20 different extensions

$allowed =  array('gif','png' ,'jpg');
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
    echo 'error';
}

@Baba Hello sir, how can we do this in the multiple file upload.? and i also get the error on $ext it mean i cannot get my file extension from this code. what should i do?

php check file extension in upload form - Stack Overflow

php file-upload
Rectangle 27 27

This is absolutely realistic and possible without using any third parties plugin.

The following snippets should give you an idea of how it could work:

$(".drop-files-container").bind("drop", function(e) {
    var files = e.originalEvent.dataTransfer.files;
    processFileUpload(files); 
    // forward the file object to your ajax upload method
    return false;
});
function processFileUpload(droppedFiles) {
         // add your files to the regular upload form
    var uploadFormData = new FormData($("#yourregularuploadformId")[0]); 
    if(droppedFiles.length > 0) { // checks if any files were dropped
        for(var f = 0; f < droppedFiles.length; f++) { // for-loop for each file dropped
            uploadFormData.append("files[]",droppedFiles[f]);  // adding every file to the form so you could upload multiple files
        }
    }

 // the final ajax call

       $.ajax({
        url : "upload.php", // use your target
        type : "POST",
        data : uploadFormData,
        cache : false,
        contentType : false,
        processData : false,
        success : function(ret) {
                 // callback function
        }
       });

 }
<form enctype="multipart/form-data" id="yourregularuploadformId">
     <input type="file" name="files[]" multiple="multiple">
</form>

Feel free to use something like this as a starting point. The browser support of this you can find here http://caniuse.com/#feat=xhr2

Of course you can add any extras you wish like progress bar, preview, animation...

if(droppedFiles.length > 0) {         for(f = 0; f < fileCount; f++) {             uploadFormData.append("files[]",droppedFiles[f]);         }     }

@Tenatious I've added some comments there. But its a normal for-loop which adds the dropped files to the form.

Keep in mind since the above code is using .bind() you would need to call the javascript after the element has been created (such as in your footer). See jQuery .bind() for more information. One other option would be to add a $(document).ready( function(){ // code }); handler. Avoiding the script to be loaded after the element was created.

One more note. You will need to preventDefault() and stopPropogation() the dragover, dragleave and the preventDefault() on the drop event. This will keep the browser from loading the local files in browser windows.

php - Drag & Drop File Upload - Stack Overflow

php jquery html5 upload drag-and-drop
Rectangle 27 11

You should pass the tmp_name of the file* to getimagesize, it will give you the size and type of the image (if it is an image). If the passed argument is a file but not an image it returns false, that will allow you to validate.

Edit: The only reliable method of image validation is to make a copy of it using GD or Imagick - getimagesize can be easily hacked.

*: I mean, the temporal file created after upload.

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $file = $_FILES['file']['tmp_name'];
    if (file_exists($file))
    {
        $imagesizedata = getimagesize($file);
        if ($imagesizedata === FALSE)
        {
            //not image
        }
        else
        {
            //image
            //use $imagesizedata to get extra info
        }
    }
    else
    {
        //not file
    }
}
$_FILES['file']['size'] = 0
$_FILES['file']['tmp_name'] = ''
$_FILES['file']['error'] = 4

Please note that it does check if it's an image, but that doesn't mean it isn't an image that has been tempered with, see: php.webtutor.pl/en/2011/05/13/ I recommend recreating the image using functions such as imagecreatefromstring and converting it to e.g. png. Arie 50 mins ago

image - PHP Validating the File Upload - Stack Overflow

php image upload pdo
Rectangle 27 7

The limit on file size uploads is limited by a LOT more than just PHP. PHP has its limits, Apache has its limits, many web services have their own limits, and then you have the limit on the /tmp directory size which could be set by user permissions on a shared host. Not to mention just running out of hard drive space!

Your php.ini looks good, but as was already suggested- check the LimitRequestBody in Apache and make sure your web service allows this.

One common solution when you need to upload very large files is to use Flash or Java on the client-side since these have access to the client's actual file system. The Flash/Java can then break the file into small pieces which are sent one at a time and re-assembled on the server side. This has multiple benefits. First, you can resume broken downloads. Second, you don't have to worry about any scripts timing out. Third, it bypasses any possible file system limits that may be in play from PHP, Apache, web services, or other sources.

Steven, now I am able to upload 100MB file by adding .htaccess file in my website folder it is like below: <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteCond %{REQUEST_URI} myuploadfolder RewriteRule ^(.*)$ mywebsite.com/index.html [R,L] </IfModule> <IfModule mod_php5.c> php_value max_input_time 0 </IfModule> I think your suggestion can help me to upload around 1GB file, but when i try to add LimitRequestBody in this .htaccess file, I get internal server error 500, so can you tell me where i should make change and how for LimitRequestBody..

httpd.apache.org/docs/current/mod/core.html#limitrequestbody Make sure that you specify in bytes LimitRequestBody 1073741824 and also make sure your web server allows this command. Some webservers have external checks in place to make sure too much data isn't being sent in a single request. This saves them bandwidth and ultimately saves them money. If it's allows, you should be able to place it at the very end of your .htaccess file. I recommend putting it in the same folder as your upload script to prevent DoS attacks on your webroot.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

1GB file upload using php - Stack Overflow

php file-upload
Rectangle 27 317

There are various ready-made plugins on doing file upload for jQuery.

Doing this kind of uploading hacks is not an enjoyable experience, so people enjoy using ready-made solutions.

You can search for more projects on NPM (using "jquery-plugin" as the keyword) or on Github.

The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload

For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.

Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.

JQuery File Uploader

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 2210

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

First, you can do some validation if you want. For example, in the onChange event of the file:

$(':file').on('change', function() {
    var file = this.files[0];
    if (file.size > 1024) {
        alert('max upload size is 1k')
    }

    // Also see .name, .type
});

Now the Ajax submit with the button's click:

$(':button').on('click', function() {
    $.ajax({
        // Your server script to process the upload
        url: 'upload.php',
        type: 'POST',

        // Form data
        data: new FormData($('form')[0]),

        // Tell jQuery not to process data or worry about content-type
        // You *must* include these options!
        cache: false,
        contentType: false,
        processData: false,

        // Custom XMLHttpRequest
        xhr: function() {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                // For handling the progress of the upload
                myXhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        $('progress').attr({
                            value: e.loaded,
                            max: e.total,
                        });
                    }
                } , false);
            }
            return myXhr;
        },
    });
});

As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.

Can I then use $_FILES in the upload.php?

This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)

Doesn't work in IE7-9

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

It's FormData who does all the magic here. Be sure to check these docs it covers all your question about multiple files and fields.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 18

<form method="post" enctype="multipart/form-data" action="index.php"></form>

To check if files are successfully updated upon submitting the form. use print_r to see results. print_r($_FILES);

when i did the "print_r($_FILES);", it displayed "Array ( )"

it means the files are not successfully uploaded.. use enctype="multipart/form-data" in your form so that you see the result of print_r($_FILES) upon form submission.

it works fine now.. continue with your work.. good luck.. Cheers :)

File not uploading PHP - Stack Overflow

php file upload