本程序是利用3.x的Firefox浏览器可以读取本地文件的特性,实现通过xmlHttPRequest上传大文件功能,并在可以上传过程中动态显示上传进度。略加修改,并与服务器端配合,可以实现断点续传等诸多功能。
本例主要是研究FireFox的file-input节点的一些特性,其他客户端应用,如Flash、Sliverlight等,在实现客户端大文件上传时,在数据传输与服务器端存储等方面,与本例的思路基本一致。
注意:文件体积似乎有临界点,但这个临界点是多少尚未确认。建议不要用此方法上传超过100M的文件。
以下是客户端javascript代码
复制代码 代码如下:
/*
* FireFoxFileSender version 0.0.0.1
* by MK winnie_mk(a)126.com
*
* 【本程序仅限于FireFox3.x版本,其他浏览器是否可以运行未做测试。】
* 【测试通过:FireFox 3.6.8 / Apache/2.2.11 (Win32) php/5.2.6 】
* ******************************************************************************
* 本程序是利用3.x的FireFox浏览器可以读取本地文件的特性
* 实现通过xmlhttpRequest上传大文件功能
* 并在可以上传过程中动态显示上传进度
* 略加修改,并与服务器端配合,可以实现断点续传等诸多功能
* 本例主要是研究FireFox的file-input节点的一些特性
* 其他客户端应用,如Flash、Sliverlight等,在实现客户端大文件上传时
* 在数据传输与服务器端存储等方面,与本例的思路基本一致
* 注意:文件体积似乎有个临界点,但这个临界点是多少尚未确认。建议不要用此方法上传超过100M的文件。
* ******************************************************************************
*/
function FireFoxFileSender(config){
var conf = config || {};
/*
* 错误信息队列
*/
this.errMsg = [];
/*
* 判断各参数是否齐备
*/
this.f = typeof conf.file == 'string' ?
document.getElementById(conf.file) : conf.file;
if(!this.f){ this.errMsg.push('Error: Not set the input file.'); }
else if(this.f.files.length else {
this.fileName = this.f.value;
/*
* 在尝试直接发送二进制流时失败,改用发送base64编码数据。
*/
this.data = (this.data = this.f.files[0].getAsDataURL())
.substr(this.data.indexOf(',') + 1);
this.length = this.data.length;
/*
* 文件实际大小
*/
this.fileSize = this.f.files[0].fileSize;
/*
* 文件类型
*/
this.contentType = this.f.files[0].fileType;
}
/*
* 服务器端接收地址
*/
this.url = conf.url;
if(!this.url){
this.errMsg.push('Error: Not set the instance url to send binary.');
}
/*
* 发送数据包的大小。默认100kb
*/
this.packageSize = conf.packageSize || 102400;
/*
* 每次发送数据包大小应为4的倍数,确保服务器端转换base64编码正确。
*/
if(this.packageSize % 4 != 0)
this.packageSize = parseInt(this.packageSize / 4) * 4;
this.onSendFinished = conf.onSendFinished || null;
this.onSending = conf.onSending || null;
this.onError = conf.onError || null;
}
FireFoxFileSender.prototype = {
/*
* 记录当前发送的数据
*/
currentData : null,
/*
* 记录读取位置
*/
position : 0,
/*
* 数据大小。该值为base64字符串的长度。
*/
length : -1,
/*
* 检查错误队列,尝试触发onError事件
*/
checkError : function(){
if(this.errMsg.length > 0){
/*
* 触发onError事件
*/
typeof this.onError == 'function' && this.onError(this.errMsg);
return;
}
},
/*
* 创建XMLHttpRequest
*/
createSender : function(){
var xhr = new XMLHttpRequest();
xhr.open('POST', this.url, true);
var _ = this;
xhr.onreadystatechange = function(){
/*
* 当服务器段响应正常,则循环读取发送。
*/
if(xhr.readyState == 4 && xhr.status == 200){
/*
* 触发onSending事件
*/
if(typeof _.onSending == 'function') _.onSending(_, xhr);
/*
* 延时发送下一次请求,否则服务器负担过重
*/
var send = setTimeout(function(){
_.send();
clearTimeout(send);
send = null;
}, 100);
}
}
return xhr;
},
/*
* 发送数据
*/
send : function(){
this.checkError();
/*
* 获取当前要发送的数据
*/
this.currentData = this.data.substr(this.position, this.packageSize);
/*
* 更改postion,模拟数据流移位
*/
this.position += this.currentData.length;
/*
* 如果读取字符串长度大于0,则发送该数据
* 否则触发onSendFinished事件
*/
if(this.currentData.length > 0) {
var xhr = this.createSender();
/*
* 自定义头部信息,通知服务器端文件相关信息
* 实际应用时可修改此部分。
*/
xhr.setRequestHeader('#FILE_NAME#', this.fileName);
xhr.setRequestHeader('#FILE_SIZE#', this.length);
xhr.setRequestHeader('#CONTENT_TYPE#', this.contentType);
xhr.send(this.currentData);
} else if(typeof this.onSendFinished == 'function') {
/*
* 触发onSendFinished事件
*/
this.onSendFinished(this);
}
},
/*
* 计算已发送数据百分比
*/
percent : function(){
if(this.length return Math.round((this.position / this.length) * 10000) / 100;
},
onSendFinished : null, //该事件是以本地数据发送完成为触发,并不是服务器端返回的完成信息。
onSending : null,
onError : null
}
/*
* 上传按钮事件
*/
function send(fileID){
var sender = new FireFoxFileSender(
/*
* 上传配置文件
*/
{
/*
* input file 元素,可以是dom节点,也可以是id的字符串值
*/
file : fileID,
/*
* 接收上传数据的服务器端地址
*/
url : 'UPLOADER.php',
/*
* 每次发送数据包的大小。可根据服务器具体情况更改。IIS6默认为200K
*/
packageSize : '200000',
/*
* 出现错误时触发该事件。本例仅在初始化时判断各参数是否齐备,并没有抛出发送过程中的错误。
*/
onError : function(arrMsg){
alert(arrMsg.join('\r\n'));
sender = null;
delete sender;
},
/*
* 发送过程中触发该事件。本例中主要用于显示进度。
*/
onSending : function(sd, xhr){
var per = sd.percent();
document.getElementById('Message').innerHTML = per + '% ';
/*
* 该判断是在最后一次发送结束后,通过xhr的onreadystatechange事件触发的
* 如果传输过程中没有其他错误,基本可以确定为服务器端接收完成
*/
if(parseInt(per) == 100){ alert('服务器端接收完成'); }
},
/*
* 该事件仅仅为【本地数据发送完成】时触发。
* 请区别本地数据发送完成和服务器端返回完成信息这两种情况
* 本例中并没有对服务器接收信息的情况做响应
* 即使服务器端没有接收和保存任何数据
* 只要确保xhr返回readyState == 4 和 status == 200
* 发送就会继续进行
* 服务器端如何返回完成信息可以通过更改接收数据页面的代码自定实现
* 然后通过对xhr.responseText的值来做判断
*/
onSendFinished : function(){
alert('本地数据发送完成');
}
}
);
sender.send();
}
以下是服务器端php代码
复制代码 代码如下:
/*
* 获取输入信息
*/
$b64 = file_get_contents("php://input");
/*
* 获取头部信息
*/
$headers = getallheaders();
$fileName = $headers['#FILE_NAME#'];
$contentType = $headers['#CONTENT_TYPE#'];
/*
* 做一些判断和处理...
*/
/*
* 以下是服务器端对发送数据的简单响应
* - 假如有数据被post过来 则输出对base64转换为二进制流后,二进制流的长度
* - 否则输出0
* 这仅仅是一个例子,并且在js端没有接收这个信息
* 同样,也可以采用在header中写入反馈信息等等方法
* 回馈信息给客户端
* 主要目的是确定上传过程中是否有其他问题出现
* 以确保上传文件完整
*/
if(!empty($b64)){
$stream = base64_decode($b64);
echo strlen($stream);
/*
* 追加方式写入文件
* 在此修改文件保存位置
*/
$file = fopen('' . $fileName , 'a');
if($file)
if(fwrite($file, $stream))
fclose($file);
} else echo '0';
客户端完整代码
复制代码 代码如下:
2
3
4
5
6
7
8
9

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
