我正在尝试通过PHP和jquery ajax实现上传文件。我可以对小文件执行此操作,但是,当我尝试上传大文件时,它显示“未知错误”。 我的jquery代码:
var data = {
data: self.parent().prev().find('img').attr('image_data'),
};
$.ajax({
url: 'banner_data/upload_remove_files',
type: 'POST',
data: data,
dataType: "json",
success: function(data) {
if (data.msg != 'error' && self.hasClass('remove_class')) {
alert('File Uploaded');
},
error: function() {
alert('Unknown error occurred');
}
});
我的PHP代码:
if (!empty($_POST['data'])) {
$file_location = $_SERVER['SERVER_NAME'].
'/pathname';
$file_name = !empty($_POST['name']) ? $_POST['name'] : '';
list($type, $raw_data) = explode(';', $_POST['data']);
list(, $raw_data) = explode(',', $raw_data);
$raw_data = base64_decode($raw_data);
if (file_put_contents($file_location.$file_name, $raw_data) === FALSE) {
$msg = 'error';
}
}
print json_encode(array(
'msg' => $msg,
'file_name' => $file_name
));
post_max_size 变量值为100 MB。因此,这不是问题。 如果问题在于有效载荷限制超出了POST请求,那么该如何解决呢?
答案 0 :(得分:0)
添加mimeType
以使用ajax发送文件
$.ajax({
url: 'banner_data/upload_remove_files',
type: 'POST',
data: data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
dataType: "json",
success: function(data) {
if (data.msg != 'error' && self.hasClass('remove_class')) {
alert('File Uploaded');
}
},
error: function() {
alert('Unknown error occurred');
}
});
答案 1 :(得分:-1)
请尝试使用此代码:
$(document).ready(function(){
$('#your_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"banner_data/upload_remove_files",
method:"POST",
data: new FormData(this),
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success:function(data)
{
if(data.msg != 'error' && self.hasClass('remove_class')) {
alert('File Uploaded');
}
},
error:function(data){
console.log(data);
}
})
});
});
并使用如下形式:
<form id="your_form" method="POST" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" name="submit" value="Upload">
</form>
关于您的 PHP代码:
// SET A DEFAULT VALUES
$msg = 'error';
$result = '';
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
# VERIFY YOUR FILE HERE
if ($fileError != 0) {
$msg = "error";
}
# UPLOAD ...
clearstatcache();
$fileNewName = uniqid(true).".".$fileActualExt; // GENERATE NAME FOR THIS FILE
$fileDestination = 'your_path/'.$fileNewName;
if (move_uploaded_file($fileTmpName, $fileDestination)) {
$msg = "Good ...";
$result = "File Path : ".$fileDestination;
}
}
echo '['.json_encode(['msg' => $msg, 'file_name' => $result]).']';
如果您不能发送大文件,即超过1 MB,则只需修改php.ini
即可:
post_max_size = 256M
upload_max_filesize = 1000M