嵌入式web服务器goahead从移植到使用之文件上传
goahead的文件上传官方也已经提供了例程可以直接用,相关代码在test.c中,如下:
1//绑定C函数uploadTest到action/uploadTest这个url
2websDefineAction("uploadTest", uploadTest);
3
4/*
5 Dump the file upload details. Don't actually do anything with the uploaded file.
6 */
7static void uploadTest(Webs *wp)
8{
9 WebsKey *s;
10 WebsUpload *up;
11 char *upfile;
12
13 websSetStatus(wp, 200);
14 websWriteHeaders(wp, -1, 0);
15 websWriteHeader(wp, "Content-Type", "text/plain");
16 websWriteEndHeaders(wp);
17 if (scaselessmatch(wp->method, "POST")) {
18 for (s = hashFirst(wp->files); s; s = hashNext(wp->files, s)) {
19 up = s->content.value.symbol;
20 websWrite(wp, "FILE: %s\r\n", s->name.value.string);
21 //文件上传后会先存储到根目录下的tmp文件夹内,并以临时文件的形式存在
22 websWrite(wp, "FILENAME=%s\r\n", up->filename);
23 //clientFilename才是上传的文件名,是自动读取出来的
24 websWrite(wp, "CLIENT=%s\r\n", up->clientFilename);
25 //文件类型
26 websWrite(wp, "TYPE=%s\r\n", up->contentType);
27 //文件大小
28 websWrite(wp, "SIZE=%d\r\n", up->size);
29 //构造路径加文件名
30 upfile = sfmt("%s/tmp/%s", websGetDocuments(), up->clientFilename);
31 //将前面存储到tmp文件夹的临时文件重命名,并且放到web/tmp/目录下
32 if (rename(up->filename, upfile) < 0) {
33 error("Cannot rename uploaded file: %s to %s, errno %d", up->filename, upfile, errno);
34 }
35 wfree(upfile);
36 }
37 websWrite(wp, "\r\nVARS:\r\n");
38 for (s = hashFirst(wp->vars); s; s = hashNext(wp->vars, s)) {
39 websWrite(wp, "%s=%s\r\n", s->name.value.string, s->content.value.string);
40 }
41 }
42 websDone(wp);
43}
对应的web存放在test/web/upload/目录下,即upload.html,内容如下:
1<html>
2<head>
3<meta charset="utf-8"/>
4<title>Uploadtitle>
5head>
6<body>
7 <h2>File Upload to HTMLh2>
8 <form method="post" action="/action/uploadTest" enctype="multipart/form-data">
9 <input type="hidden" name="MAX_FILE_SIZE" value="30000">
10 <table border="0">
11 <tr><td>Nametd><td><input type="text" name="Name">td>tr>
12 <tr><td>Addresstd><td><input type="text" name="Address">td>tr>
13 <tr><td>File:td><td><input type="file" name="file">td>tr>
14 table>
15 <input type="submit" value="send">
16 <input type="reset" value="cancel">
17 form>
18body>
19html>
在上传文件前,我们先要看一下,goahead服务器运行的根目录(注意这个根目录就是使用--home参数指定的目录)下是否有一个tmp文件夹,如果不存在则先创建一个tmp文件夹,这个文件夹就是用来临时存储服务器收到的文件,如果不想使用这个文件夹可以修改配置文件me.h中宏(ME_GOAHEAD_UPLOAD_DIR)定义的内容为你想要设置的目录;在上面uploadTest函数的第30行指定了将最终得到的文件放在哪儿,这里是web/tmp/目录下,所以还要看下web目录下是否有一个tmp文件夹,如果不存在则先创建一个。
前面的步骤做完后,就可以启动goahead服务器了,用以下命令启动goahead服务器:
./goahead-test -v --home ../../../test/ web
启动后,用浏览器打开这个网页,界面如下:
选择文件后点击send按钮,文件就上传成功了,并且页面显示了上传的文件详情:





