I always got an invalid file type error in uploading csv file in codeigniter. I already googled for possible mime types for csv and still nothing works. so I bother echoing the echo $_FILES['userfile']['type']; and I got this MIME type : 'application/force-download'. Below is a snippet from the controller and a snippet from the view
Controller:
public function upload_file()
{
$status = "";
$msg = "";
$file_element_name = 'userfile';
if (empty($_POST['title']))
{
$status = "error";
$msg = "Please enter a title";
}
if ($status != "error")
{
$config['upload_path'] = './uploads/csv_list/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt|.csv';
$config['max_size'] = 1024 * 8;
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$status = "success";
$msg = "File successfully uploaded";
}
@unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
View:
<input type="text" name="title" id="title" value="a" style ="display:none"/>
<p>
<input type="text" name="title" id="title" value="a" style ="display:none"/>
<label for="userfile">Upload CSV File</label>
<input type="file" name="userfile" id="userfile" size="20" />
<input type="submit" name="submit" id="submit" value ="Upload"/>
</p>
<script>
$(function () {
$('#upload_file').submit(function (e) {
e.preventDefault();
$.ajaxFileUpload({
url: '../upload/upload_file/',
secureuri: false,
fileElementId: 'userfile',
dataType: 'json',
data: {
'title': $('#title').val()
},
success: function (data, status) {
if (data.status != 'error') {
$('#files').html('<p>Reloading files...</p>');
// refresh_files();
// $("#userfile").replaceWith("<input type=\"file\" id=\"userfile\" size = \"20\" />");
$('#files').html('File Uploaded');
// $('#title').val('');
}
alert(data.msg);
}
});
return false;
});
});
</script>
The problem here is that different web browser gets different ideas on what type a file is. Since CodeIgniter's upload class is dependent of file types, this can get messy.
I followed several instruction to add more types to the fields in the config/
but neither did the trick.
I ended up with allowing all types $config['allowed_types'] = '*'
and validated like this instead:
if (in_array(end(explode('.', $str_file_name)), array('php')))
return FALSE;
or in your case:
$arr_validate = array('gif', 'jpg', 'png', 'doc', 'txt', 'csv');
if ( ! in_array(end(explode('.', $str_file_name)), $arr_validate))
return FALSE;
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.