在项目开发的过程中,可能会牵扯到大量的图片,PDF,ZIP等文件。这些文件不会放在本地或者本项目下。他们会有一个专门的图片服务器。如果你够细心的话你会发现,你从百度上下载下来的图片的网址都会有http://img.qkhl.net 注意这个就是一个图片服务器。实现文件上传到远程服务器,我用的是plupload来实现的。http://www.cnblogs.com/2050/p/3913184.html 插件可以在官网上download
用 plupload上传的思路是:在本地选择文件上传,在远程服务器那边接收,并且返回图片地址,在保存到数据库中即可。在上传的过程中要注意的是路径要保证正确。
plupload功能比较强大,不仅可以实现远程上传,也可以实现本地上传。
*html代码:
<div class="cont_box cont_boxH2 uploadBook">
<div class="cont_inner">
<div class="add_title clearself">
<span class="fl">位置:教辅图书列表</span>
<script type="text/javascript" src="<?= base_url('script/plupload/plupload.full.min.js') ?>"></script>
<script type="text/javascript" src="<?= base_url('script/plupload/jquery-ui.min.js') ?>" charset="UTF-8"></script>
<script type="text/javascript" src="<?= base_url('script/plupload/i18n/zh_CN.js') ?>"></script>
<script type="text/javascript" src="<?= base_url('script/plupload/jquery.ui.plupload/jquery.ui.plupload.min.js') ?>" charset="UTF-8"></script>
</div>
<div class="stepNumb">
2、上传图书
</div>
<div class="stepTips inline-block-parent">
<div class="step stepActive inline-block">1<div class="stepFont stepF1 stepFontActive">添加图书信息</div></div>
<div class="line lineActive inline-block"></div>
<div class="step stepActive inline-block">2<div class="stepFont stepFontActive">上传图书</div></div>
<div class="line lineActive inline-block"></div>
<div class="step inline-block">3<div class="stepFont stepF1">设置图书价格</div></div>
</div>
<!--上传pdf开始-->
<form action="" method="post" enctype="multipart/form-data" id="upapk">
<!--第一个开始-->
<div class="upload">
<span class="inline-block">上传PDF:</span>
<div class="uploadInput inline-block">
<input type="text" id="filename" style="width: 80%;height: 100%;">
<div class="file fr">
<a href="javascript:;" id="list_browse" >选择文件</a>
</div>
</div>
<span id="jd"></span><input type="hidden" name="filepath" id="filepath" >
</div>
<div class="book_box" id="file-list"></div>
<!--第一个结束-->
<!--第二个开始-->
<div class="upload">
<span class="inline-block">上传PDF:</span>
<div class="uploadInput inline-block">
<input type="text" id="filename1" style="width: 80%;height: 100%;">
<div class="file fr">
<a href="javascript:;" id="list_browse1" >选择文件</a>
</div>
</div>
<span id="jd1"></span><input type="hidden" name="filepath" id="filepath" >
</div>
<div class="book_box" id="file-list1"></div>
<!--第二个结束-->
<div class="nextStep">
<input type="button" id="uploadfile" style="background-color: initial;" value="提交" />
</div>
</form>
<!--上传结束-->
<script src="<?= base_url('script/index.min.js') ?>"></script>
<script>
function DropDown(el) {
this.dd = el;
this.initEvents();
}
DropDown.prototype = {
initEvents: function () {
var obj = this;
obj.dd.on('click', function (event) {
var that = this;
$(that).addClass("active");
$(".li", that).on({
mouseover: function () {
$(this).addClass("liActive");
},
mouseout: function () {
$(this).removeClass("liActive");
},
click: function () {
var optionValue = $(this).html();
$(".avctiveVal", that).text(optionValue);
}
});
$(".dropdown", that).stop().slideToggle(500);
$(that).siblings().find(".dropdown").slideUp("fast", function () {
$(that).siblings().removeClass("active");
});
event.stopPropagation(500);
});
}
};
$(function () {
var dd1 = new DropDown($('#dd1'));
v`ar dd2 = new DropDown($('#dd2'));
var dd3 = new DropDown($('#dd3'));
var dd4 = new DropDown($('#dd4'));
var dd5 = new DropDown($('#dd5'));
$(document).click(function () {
$('.wrapper-dropdown-2 .dropdown').slideUp(500);
$('.wrapper-dropdown-2').removeClass("active");
});
})
</script>
<script type="text/javascript">
//上传参数
var callback_url = '';
var callback_url1 = '';
var file_path = "qw<?php echo date("Y-h-d"); ?>";
//图片列表中的上传按钮
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: ['list_browse', 'list_browse1'],
url: "http://img.qkhl.net/test/pdf_booky.php",
chunk_size: '1gb',
unique_names: true,
multipart: true,
filters: {//uploader包含 的那些特性
max_file_size: '1024mb',
chunk_size: '1mb',
mime_types: [
{title: "Image pdf", extensions: "pdf"}
]
},
flash_swf_url: "<?= base_url('script/plupload/Moxie.swf') ?>",
silverlight_xap_url: "<?= base_url('script/plupload/Moxie.xap') ?>",
preinit: {
UploadFile: function (up, file) {//当一个文件被上传时触发
up.setOption('multipart_params', {callback_url: [callback_url, callback_url1], file_path: file_path});
}
},
init: {
PostInit: function (up) {//init执行完以后要执行的触发
document.getElementById('uploadfile').onclick = function () {
if (parseInt(up.total.queued) <= 0)
{
alert("请选择上传文件");
uploader.stop();
return false;
}
uploader.start();
return false;
};
},
FilesAdded: function (up, file) {//用户选择文件触发
document.getElementById('filename').value = file[0]['name'];
document.getElementById('filename1').value = file[0]['name'];
},
UploadProgress: function (up, file) {//文件上传中触发
//alert(file.percent);
document.getElementById("jd").innerHTML = file.percent;
document.getElementById("jd1").innerHTML = file.percent;
},
FileUploaded: function (up, file, info) {//文件上传后触发
if (info['status'] != 200)
{
alert(info['result']['message']);
up.stop();
return false;
} else {
var str = info.response;
alert(str)
var json = eval('(' + str + ')');
if (json['status'] == 'success')
{
alert(json);
var img_s = json['result']['imgpath'];
alert(img_s)
}
else
{
//alert(info['result']['message']);
up.stop();
return false;
}
}
},
Error: function (up, args) {//上传错误时触发
alert('上传失败,文件错误!');
up.stop();
return false;
}
}
});
uploader.init();
</script>
*服务器那边的接收文件:
header('Access-Control-Allow-Origin:*'); //html5跨域接收文件
date_default_timezone_set('PRC');
@set_time_limit(5 * 60);
* 接收参数
$file_path = isset($_POST['file_path']) ? $_POST['file_path'] : ''; //文件路径新建的文件夹
$callback_url = isset($_POST['file_path']) ? $_POST['callback_url'] : ''; //回调地址
$host_url = "task_cloud.qkhl.net"; //回调域名
$url = $host_url . $callback_url . '?1=1';
//循环POST参数
foreach ($_POST as $k => $v) {
if ($k != 'file_path' && $k != 'callback_url') {
$url .= '&' . $k . '=' . $v;
}
}
if (!$file_path) {
die('{"status" : "success", "result" : {"code": 201, "message": "data is null"}}');
}
//sleep(1); //为了显示进度条
$targetDir = $file_path;
$cleanupTargetDir = true;
$maxFileAge = 5 * 3600;
if (!file_exists($targetDir)) {
@mkdir($targetDir);
}
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}
$filePath = $targetDir . '/' . $fileName;
$ys_filePath = $targetDir . '/ys_' . $fileName;
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('{"status" : "error", "result" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . '/' . $file;
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
die('{"status" : "error", "result" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
die('{"status" : "error", "result" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
}
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
die('{"status" : "error", "result" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
} else {
if (!$in = @fopen("php://input", "rb")) {
die('{"status" : "error", "result" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($out);
@fclose($in);
if (!$chunks || $chunk == $chunks - 1) {
rename("{$filePath}.part", $filePath);
die('{"status" : "success", "result": {"imgpath" : "' . $filePath . '"}}');
}