nginx服务器实现上传下载文件的实例代码

 更新时间:2024年02月01日 11:18:05   作者:三遍猪  
这篇文章主要介绍了nginx服务器实现上传下载文件的实例代码,本文通过代码给大家介绍的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下

下载

更新配制文件,添加如下字段,这里用alias实现把嵌入式开发板的根目录全部映射过去,

location /download {
    alias   /;
    autoindex on; 
    autoindex_localtime on;
    autoindex_exact_size off;
} 

执行,

$ ./nginx/sbin/nginx -p ./nginx -s reload

上传

需要有nginx的源码,重新编译nginx,添加上传模块,上传进度模块,

$ ./configure --add-module=$parent_path/nginx-upload-module-2.3.0 --add-module=$parent_path/nginx-upload-progress-module-0.8.4
$ make
$ make install

注意上传进度模块,到0.9版本有一个不兼容的更改,

in version 0.9.0 there is INCOMPATIBLE CHANGE: JSONP is now the default output of the progress probes. If you rely on this module serving the deprecated java output use:

upload_progress_java_output
in the progress probe location.

添加配置文件,

location /upload {  
    upload_pass     /;  
    # upload_cleanup 400 404 499 500-505;  
    upload_store    /boot;  
    upload_store_access user:rw;  
    # upload_limit_rate 128k;  
    upload_set_form_field "${upload_field_name}_name" $upload_file_name;  
    upload_set_form_field "${upload_field_name}_content_type" $upload_content_type;  
    upload_set_form_field "${upload_field_name}_path" $upload_tmp_path;  
    upload_aggregate_form_field "${upload_field_name}_md5" $upload_file_md5;  
    upload_aggregate_form_field "${upload_field_name}_size" $upload_file_size;  
    upload_pass_form_field "^.*$";  
}

建立html测试,使用fcgi,

printf("<form method=\"POST\" enctype=\"multipart/form-data\" action=\"uploademmc\"\n");
printf("<p>File Upload:\n");
printf("<input type=\"file\" name=\"file\" value=\"\">\n");
printf("<p>\n");
printf("<input type=\"submit\" name=\"uploademmc\" value=\"uploademmc\">\n");
printf("<p>\n");
printf("</form>\n");

上传,0000000001即为新上传的文件,这里必须用脚本在上传结束后来执行重命名操作,

root@zynqmp:~# ls -l /boot
total 53172
-rw-------    1 root     root         31428 Jan 26 16:11 0000000001
-rw-r--r--    1 root     root      14283264 Jan 26 12:06 Image
-rwxr-xr-x    1 root     root      19311212 Jan  1  1970 MWM178_V1_U6_V1.bit
-rw-r--r--    1 root     root       1118392 Jan 26 06:47 boot.bin
-rw-r--r--    1 root     root      19634147 Jan 26 00:56 rootfs.ext4.gz.uboot
-rw-r--r--    1 root     root         29091 Jan 26 06:47 system.dtb

上传使用post方法,后端接收到的字符串为如下格式,可以看到文件名在file_name字段中,可利用环境变量REQUEST_URI提取出来即可,

------WebKitFormBoundarygKAThjQRpvOwowzR
Content-Disposition: form-data; name="file_name"

11.PNG
------WebKitFormBoundarygKAThjQRpvOwowzR
Content-Disposition: form-data; name="file_content_type"

image/png
------WebKitFormBoundarygKAThjQRpvOwowzR
Content-Disposition: form-data; name="file_path"

/boot/0023791667
------WebKitFormBoundarygKAThjQRpvOwowzR
Content-Disposition: form-data; name="file_md5"

0276e88e6161ac806d46ee0afb45976e
------WebKitFormBoundarygKAThjQRpvOwowzR
Content-Disposition: form-data; name="file_size"

17734
------WebKitFormBoundarygKAThjQRpvOwowzR
Content-Disposition: form-data; name="uploademmc"

uploademmc
------WebKitFormBoundarygKAThjQRpvOwowzR--

FCGI_ROLE=RESPONDER
SCRIPT_FILENAME=./nginx/html/index.cgi
QUERY_STRING=
REQUEST_METHOD=POST
CONTENT_TYPE=multipart/form-data; boundary=----WebKitFormBoundarygKAThjQRpvOwowzR
CONTENT_LENGTH=706
SCRIPT_NAME=/index.cgi
REQUEST_URI=/uploademmc

上传进度模块需要前端js协助,配置文件,前面提到的0.9版本有一个不兼容的更改,如果需要和老版本兼容,需要在location ^~ /progress中添加upload_progress_java_output

http {
    ...
    upload_progress proxied 5m;
    
    server {
        ...

        location = / {
            fastcgi_pass 127.0.0.1:8088;
            fastcgi_index index.cgi;
            include fastcgi.conf;
        }

        location /download {
            alias   /;
            autoindex on; 
            autoindex_localtime on;
            autoindex_exact_size off;
        } 

        location /upload {  
            upload_pass     /;  
            # upload_cleanup 400 404 499 500-505;  
            upload_store    /boot;  
            upload_store_access user:rw;  
            # upload_limit_rate 128k;  
            client_max_body_size 8g;
            upload_set_form_field "${upload_field_name}_name" $upload_file_name;  
            upload_set_form_field "${upload_field_name}_content_type" $upload_content_type;  
            upload_set_form_field "${upload_field_name}_path" $upload_tmp_path;  
            upload_aggregate_form_field "${upload_field_name}_md5" $upload_file_md5;  
            upload_aggregate_form_field "${upload_field_name}_size" $upload_file_size;  
            upload_pass_form_field "^.*$";  
            track_uploads proxied 30s;
        }

        location ^~ /progress {
            # report uploads tracked in the 'proxied' zone
            report_uploads proxied;
            # upload_progress_java_output;
        }

        location ~ \.js$ {
            root html;
        }

设置参数client_max_body_size 8g,否则上传时会报错413 Request Entity Too Large,编写html,

printf("<form id=\"upload\" method=\"POST\" enctype=\"multipart/form-data\" action=\"upload\" οnsubmit=\"openProgressBar(); return true;\"\n");
printf("<p>File Upload:\n");
printf("<input type=\"file\" name=\"file\" value=\"\">\n");
printf("<p>\n");
printf("<input type=\"submit\" name=\"upload\" value=\"upload\">\n");
printf("<p>\n");
printf("</form>\n");
printf("<div>\n");
printf("<div id=\"progress\" style=\"width: 400px; border: 1px solid black\">\n");
printf("<div id=\"progressbar\" style=\"width: 1px; background-color: blue; border: 1px solid white\">&nbsp;</div>\n");
printf("</div>\n");
printf("<div id=\"tp\">(progress)</div>\n");
printf("</div>\n");

添加js文件,

interval = null;

function openProgressBar() {
 /* generate random progress-id */
 uuid = "";
 for (i = 0; i < 32; i++) {
  uuid += Math.floor(Math.random() * 16).toString(16);
 }
 /* patch the form-action tag to include the progress-id */
 document.getElementById("upload").action="/upload?X-Progress-ID=" + uuid;

 /* call the progress-updater every 1000ms */
 interval = window.setInterval(
   function () {
     fetch(uuid);
   },
   1000
 );
}

function fetch(uuid) {
 req = new XMLHttpRequest();
 req.open("GET", "/progress", 1);
 req.setRequestHeader("X-Progress-ID", uuid);
 req.onreadystatechange = function () {
  if (req.readyState == 4) {
   if (req.status == 200) {
    /* poor-man JSON parser */
    var upload = eval(req.responseText);

    document.getElementById('tp').innerHTML = upload.state;

    /* change the width if the inner progress-bar */
    if (upload.state == 'done' || upload.state == 'uploading') {
     bar = document.getElementById('progressbar');
     w = 400 * upload.received / upload.size;
     bar.style.width = w + 'px';
    }
    /* we are done, stop the interval */
    if (upload.state == 'done') {
     window.clearTimeout(interval);
    }
   }
  }
 }
 req.send(null);
}

测试一下,chrome自己也会统计上传进度,标题栏开始小圆圈刷新,

在这里插入图片描述

总结

以上就是nginx服务器实现上传下载文件的实例代码的详细内容,更多关于nginx上传下载文件的资料请关注脚本之家其它相关文章!

相关文章

  • nginx php-fpm 小VPS 优化

    nginx php-fpm 小VPS 优化

    小VPS受系统资源的限制,访问量过大,超过系统所能承受的极限时,有一部分请求就会502了。在系统资源够用的情况,优化nginx,php-fpm,以及系统本身
    2016-05-05
  • 升级nginx以支持http2的方法

    升级nginx以支持http2的方法

    本篇文章主要介绍了升级nginx以支持http2的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-03-03
  • 加速nginx性能: 开启gzip和缓存

    加速nginx性能: 开启gzip和缓存

    nginx 是一个高性能的 Web 服务器,之前也写过一些关于 nginx 的文章。为了提高博客的响应速度,可以从设置 nginx 的 gzip 和缓存这2方面入手。为字体开启 gzip 和缓存能大大减少带宽的消耗
    2017-03-03
  • nginx http 499错误码详解以及解决办法

    nginx http 499错误码详解以及解决办法

    HTTP状态码出现499错误有多种情况,499错误是什么?这篇文章主要给大家介绍了关于nginx http 499错误码以及解决办法的相关资料,文中介绍的非常详细,需要的朋友可以参考下
    2024-01-01
  • Nginx用户认证配置方法详解(域名/目录)

    Nginx用户认证配置方法详解(域名/目录)

    Nginx超级强大它可以单独为一个域名设置用户认证,方法也很简单我们只要生成用户认证的用户名和密码,然后再Nginx添加auth认证配置即可
    2013-08-08
  • Nginx0.5.33+PHP5.2.5(FastCGI)搭建胜过Apache10倍的Web服务器

    Nginx0.5.33+PHP5.2.5(FastCGI)搭建胜过Apache10倍的Web服务器

    Nginx 0.5.31 + PHP 5.2.4(FastCGI)搭建可承受3万以上并发连接数,胜过Apache 10倍的Web服务器的第2版,经过了多台服务器的测试。
    2009-10-10
  • nginx反向代理导致session失效的问题解决

    nginx反向代理导致session失效的问题解决

    这篇文章主要介绍了nginx反向代理导致session失效的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • 排查服务器异常流量教程详解

    排查服务器异常流量教程详解

    这篇文章主要为大家介绍了排查服务器异常流量教程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • nginx支持codeigniter的pathinfo模式url重写配置写法示例

    nginx支持codeigniter的pathinfo模式url重写配置写法示例

    这篇文章主要介绍了nginx支持codeigniter的pathinfo模式url重写配置写法示例,pathinfo模式是一种开发框架都爱用的路由模式,需要的朋友可以参考下
    2014-07-07
  • nacos集群搭建Nginx负载均衡的操作详解

    nacos集群搭建Nginx负载均衡的操作详解

    这篇文章主要介绍了nacos集群搭建Nginx负载均衡的详细操作,文中通过代码示例和图文介绍的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-01-01

最新评论