文件上传的几种方法

当我们想把文件上传到web服务器上时,通常有如下几种方法:

方法1、html(form)+nginx(文件上传模块)+php:这种方式最复杂。一般不用。实现过程说明如下:
步骤一:form中,action=“/upload”. 指定一个目录,而不是一个文件。method都是POST.
步骤二:在nginx中,安装文件上传模块进行编译安装。然后配置文件中,对/upload访问目录进行配置。指定相关参数。并指定后端处理文件上传的php文件。经过nginx转手,后端php获取的参数就是nginx传递的,不是前端form过来的。
步骤三:后端php文件对传递过来的文件信息进行处理。需要配置php.ini,允许上传文件。
以上实现的方法,在之前的html备份文件中存在。可以找到(html201908221746)。nginx的备份文件:nginx.conf201908242138。

方法2、html(form)+nginx+php:这种方式常见,配置比较简单。
步骤一:form中,action=“/test.php”. 指定后端php文件,method都是POST.
步骤二:nginx只做为web服务存在
步骤三:php.ini中启用文件上传,指定文件临时存储路径等等。
步骤四:php文件处理前端传递过来的上传文件。
比如:
html:
<form enctype="multipart/form-data" action="test.php" method="post">
选择文件:<input type="file" name="file" > <br>
<input type="submit" value="上传">

php:
$uploaddir = '/tmp/test/' ;
$uploadfile = $uploaddir.basename ( $_FILES [ 'file' ][ 'name' ]);
if ( move_uploaded_file ( $_FILES [ 'file' ][ 'tmp_name' ], $uploadfile )) {
echo "File is valid, and was successfully uploaded.\n" ;
} else {
echo "Possible file upload attack!\n" ;
}
echo 'Here is some more debugging info:' ;

方法3、curl+nginx+php:这个和方法2类似。只是上传文件客户端方法变化。由html的form变成了curl。这就更方便了。
curl -F "file=@/etc/passwd" http://10.10.0.245/test.php
php:
$uploaddir = '/tmp/test/' ;
$uploadfile = $uploaddir.basename ( $_FILES [ 'file' ][ 'name' ]);
if ( move_uploaded_file ( $_FILES [ 'file' ][ 'tmp_name' ], $uploadfile )) {
echo "File is valid, and was successfully uploaded.\n" ;
} else {
echo "Possible file upload attack!\n" ;
}
echo 'Here is some more debugging info:' ;

注意:curl的file关键字和php中的$_FILES [ 'file' ][ 'tmp_name' ]中的file关键字对应。其实等同于form的input的name。

方法4、html(form)+js+nginx+php:这种方式体验更好。前端上传文件时,不需要刷新页面,也不需要重新打开一个新的窗口。在当前窗口即可提示上传文件结果。

其中方法4和其他方式的不同点是客户端不同,前面3种方法都是通过web 浏览器提交文件上传。需要交互操作。而方法4,就通过通过脚本实现上传。可以解决不少问题。

 

posted @ 2019-10-11 15:16  路过苏州  阅读(3512)  评论(0编辑  收藏  举报