我是laravel的新手,我正在尝试将pl uploader集成到图像上传中。
上传图片时出现未知状态错误。
以下是我在视图中使用的脚本:
var uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
browse_button : 'bg_upload', // you can pass an id...
container: document.getElementById('bg_container'), // ... or DOM Element itself
url : "{{ url('/') }}/image-upload?_token="+$('meta[name="csrf-token"]').attr('content'),
unique_names : false,
max_file_count: 1,
multi_selection: true,
flash_swf_url : "{{ URL::asset('admin/js/pluploader/Moxie.swf') }}",
silverlight_xap_url : "{{ URL::asset('admin/js/pluploader/Moxie.xap') }}",
filters : {
max_file_size : '60mb'
},
init: {
FileUploaded: function (up, file) {
var upload_path = "{{ url('/uploads') }}";
var img = jQuery('<img alt="click to change image" src="'+upload_path+file.name+'" style="width:auto; max-height:400px;">');
jQuery("#bg_upload").html(img);
},
FilesAdded: function(up, files) {
jQuery("#progress_file").css("display","block");
plupload.each(files, function(file) {
var img_type = file.name;
jQuery("#progress_file").append('<div id="' + file.id + '" >' + img_type + ' (' + plupload.formatSize(file.size) + ')<b></b></div>');
});
uploader.start();
},
UploadProgress: function(up, file) {
jQuery("#"+file.id).find("b").html('<span>' + file.percent + "%</span>");
},
UploadComplete: function () {
jQuery("#progress_file").html("");
jQuery("#progress_file").css("display","none");
},
Error: function(up, err) {
console.log("\nError #" + err.code + ": " + err.message);
//document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
}
}
});
uploader.init();
这是我定义的路线:
Route::post('/image-upload', 'ProductsController@upload_image');
这是控制器的upload_image
功能:
public function upload_image()
{
if( ! ini_get('date.timezone') )
{
date_default_timezone_set('GMT');
}
// Make sure file is not cached (as it happens for example on iOS devices)
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
/*
// Support CORS
header("Access-Control-Allow-Origin: *");
// other CORS headers if any...
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit; // finish preflight CORS requests here
}
*/
// 5 minutes execution time
@set_time_limit(5 * 60);
// Uncomment this one to fake upload time
// usleep(5000);
// Settings
$targetDir = base_path().'/uploads';
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
@mkdir($targetDir);
}
//echo $targetDir;
// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}';
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}
// Open temp file
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}';
}
if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}';
}
// Read binary input stream and append it to temp file
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}';
}
} else {
if (!$in = @fopen("php://input", "rb")) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}';
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($out);
@fclose($in);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
$data = '{"jsonrpc" : "2.0", "result" : null, "id" : "id"}';
return response()->json($data);
//return '{"jsonrpc" : "2.0", "result" : null, "id" : "id"}';
}
谁能告诉我哪里错了。
提前致谢。
答案 0 :(得分:0)
代码开始工作。可能是缓存问题。我不知道会发生什么,代码开始上传。
这是我的最终代码:
我在视图中使用的上传器脚本:
var uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
browse_button : 'bg_upload', // you can pass an id...
container: document.getElementById('bg_container'), // ... or DOM Element itself
url : "{{ url('/') }}/image-upload?_token="+$('meta[name="csrf-token"]').attr('content'),
unique_names : false,
max_file_count: 1,
multi_selection: false,
flash_swf_url : "{{ URL::asset('admin/js/pluploader/Moxie.swf') }}",
silverlight_xap_url : "{{ URL::asset('admin/js/pluploader/Moxie.xap') }}",
filters : {
max_file_size : '60mb'
},
init: {
FileUploaded: function (up, file) {
var upload_path = "{{ URL::asset('uploads') }}";
var img = jQuery('<img alt="click to change image" src="'+upload_path+"/"+file.name+'" style="width:100%;">');
jQuery("#bg_container").addClass("no-border");
jQuery("#bg_upload").html(img);
},
FilesAdded: function(up, files) {
jQuery("#progress_file").css("display","block");
plupload.each(files, function(file) {
var img_type = file.name;
jQuery("#progress_file").append('<div id="' + file.id + '" >' + img_type + ' (' + plupload.formatSize(file.size) + ')<b></b></div>');
});
uploader.start();
},
UploadProgress: function(up, file) {
jQuery("#"+file.id).find("b").html('<span>' + file.percent + "%</span>");
},
UploadComplete: function () {
jQuery("#progress_file").html("");
jQuery("#progress_file").css("display","none");
},
Error: function(up, err) {
console.log("\nError #" + err.code + ": " + err.message);
//document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
}
}
});
uploader.init();
这是路线代码:
Route::post('/image-upload', 'ProductsController@upload_image');
控制器中的图片上传代码:
public function upload_image(Request $request)
{
if( ! ini_get('date.timezone') )
{
date_default_timezone_set('GMT');
}
// Make sure file is not cached (as it happens for example on iOS devices)
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// 5 minutes execution time
@set_time_limit(5 * 60);
// Uncomment this one to fake upload time
// usleep(5000);
// Settings
$targetDir = public_path().'/uploads';
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
@mkdir($targetDir);
}
// Get a file name
if ($request->input('name')) {
$fileName = $request->input('name');
} elseif (!empty($_FILES)) {
$fileName = $request->image->getClientOriginalName();
} else {
$fileName = uniqid("file_");
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
// Chunking might be enabled
$chunk = $request->input("chunk") ? intval($request->input("chunk")) : 0;
$chunks = $request->input("chunks") ? intval($request->input("chunks")) : 0;
// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}';
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}
// Open temp file
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}';
}
if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}';
}
// Read binary input stream and append it to temp file
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}';
}
} else {
if (!$in = @fopen("php://input", "rb")) {
$data = '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}';
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($out);
@fclose($in);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
$data = '{"jsonrpc" : "2.0", "result" : null, "id" : "id"}';
return response()->json($data);
}