上篇文章nginx+fcgi+c/c++搭建高效率應用
http://blog.csdn.net/marising/archive/2009/02/24/3932938.aspx
有人問到,fcgi怎麼處理上傳檔案。我試了一下,其實比較簡單。
1.upload.html檔案,
<div id="pandaloader"><br /><div id="uploader"><br /><form id="upload" enctype="multipart/form-data" action="/upload.cgi" method="post"><br /><input name="file" type="file"><br /><input type="submit" value="Upload"><br /></form><br /></div><br /></div>
2.fcgiupload.cpp檔案,改寫的上次例子,如果是upload.cgi就處理,其他的不處理。
#include <iostream><br />#include <stdlib.h><br />#include <stdio.h><br />#include <fcgiapp.h><br />#include <string.h><br />#include <fcgi_stdio.h><br />int main() {<br />int count = 0;<br />while (FCGI_Accept() >= 0) {<br />count++;<br />char* req_uri = getenv("REQUEST_URI");<br />printf("Content-type: text/html/r/n/r/n");<br />printf("Request_uri:%s<br/>",req_uri);<br />char* cont_type = getenv("CONTENT_TYPE");<br />printf("Content_type:%s<br/>",cont_type);<br />if ( strcmp(req_uri,"/upload.cgi") == 0) {<br />char *contentLength = getenv("CONTENT_LENGTH");<br />int len;<br />if (contentLength != NULL) {<br />len = strtol(contentLength, NULL, 10);<br />} else {<br />len = 0;<br />}<br />printf("Content_length:%d<br/>",len);<br />int i, ch;<br />FILE* localfile = fopen("/home/lhb/upload/file1", "w");<br />printf("Standard input:<br><pre>");<br />for (i = 0; i < len; i++) {<br />if ((ch = getchar()) < 0) {<br />printf("Error: Not enough bytes received on standard input<p>/n");<br />break;<br />}<br />putchar(ch);<br />fputc(ch,localfile);<br />}<br />printf("</pre>");<br />fflush(localfile);<br />fclose(localfile);<br />} else {<br />printf("FastCGI Hello! (C, fcgi_stdio library)"<br />"Request number %d running on host %s Process ID: %d",count, getenv("SERVER_NAME"), getpid());<br />}<br />}<br />return 0;<br />}<br />
3.上傳後,頁面顯示如下,從Standard input:開始,都是接收的資料
Content_type:multipart/form-data; boundary=---------------------------2571883601823556076521314992<br />Content_length:2668<br />Standard input:<br />-----------------------------2571883601823556076521314992<br />Content-Disposition: form-data; name="file"; filename="nginx.conf"<br />Content-Type: application/octet-stream<br />內容..........<br />-----------------------------2571883601823556076521314992<br />
4.關於檔案上傳的協議部分,multipart form-data部分,請參考如下串連來處理。
http://yefeng.javaeye.com/blog/315847
5.關於圖片等二進位的內容,把例子中讀(從FCGI_stdin中)/寫(本地檔案),都改為fread/fwrite就可以了。
6.nginx有upload module,有興趣可以試試。
http://brainspl.at/articles/2008/07/20/nginx-upload-module
7.nginx的上傳大小有限制,請修改nginx.conf
client_max_body_size 10m
8.最後說一下spwan-cgi
我用如下的命令執行
$./spawn-fcgi -a 127.0.0.1 -p 9000 -u www -f fcgiupload
$spawn-fcgi.c.230: child exited with: 2
提示如上行,死活起不來。
我改為
$ ./spawn-fcgi -a 127.0.0.1 -p 9000 fcgiupload
$spawn-fcgi.c.207: child spawned successfully: PID: 2495
就可以了,那位能解釋一下?