stack stack - 1 month ago 13
Javascript Question

How can I make a upload .txt file form?

Here is my codes:

HTML:

<form id="form_id" action="#" accept-charset="UTF-8" enctype="multipart/form-data">
<div>
<label for="files" class="drop-files-container">drag here</label>
<input id="files" type="file" name="file[]" style="visibility:hidden;">
</div>
</form>


JavaScript:

$('#files').on('change',function() {
var files = $(this)[0].files;
processFileUpload(files);
return false;
});

function processFileUpload(droppedFiles) {
var uploadFormData = new FormData($("#form_id")[0]);
if(droppedFiles.length > 0) {
for(var f = 0; f < droppedFiles.length; f++) {
uploadFormData.append("file",droppedFiles[f]);
}
}
$.ajax({
url : "compareList.php",
type : "POST",
data : uploadFormData,
contentType: "application/x-www-form-urlencoded;charset=utf-8",
cache : false,
contentType : false,
processData : false,
dataType : "json",
success : function(data) {
console.log(data);
}
});
}


PHP:

$arr = array();
$file = $_FILES['file'];
$handle = fopen($file, "r");

header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));


And my code returns this:


Warning: fopen() expects parameter 1 to be a valid path, array given in C:\xampp\htdocs\comparelist_php\compareList.php on line 6

{"message":"ERROR","code":1337}


How can I fix it?

Answer

The problem is that $_FILES['file'] is an array, you have to use $_FILES['file']['tmp_name'].

Taken from the PHP documentation :

The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.

$_FILES['userfile']['name']

  • The original name of the file on the client machine.

$_FILES['userfile']['type']

  • The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

$_FILES['userfile']['size']

  • The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']

  • The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']

  • The error code associated with this file upload.