|
C言語(というかC++)でPOSTしたいとき用のプログラムです。 サンプルプログラムの動かし方 †
主要な関数: post_file †ヘッダを作って送るだけなのですがboundaryでちょっとはまりました。 今回はboundaryは「software-defined-laboratory」にしています。開始の時は--を前に付けて「--software-defined-laboratory」、終了の時は--を前と後ろに着けて「--software-defined-laboratory--」とするのですが、改行コード「\r\n」を前後、すなわち「\r\n--software-defined-laboratory--\r\n」としなければならないことになかなか気付かず... int post_file(const char *hostname, const char *filename)
{
int sock = tcp_connect(hostname, 80);
char header[1024];
char pre[1024];
char post[1024];
char boundary[] = "software-defined-laboratory";
sprintf(pre, "--%s\r\n", boundary);
sprintf(pre + strlen(pre), "Content-Disposition: form-data; ");
sprintf(pre + strlen(pre), "name=\"userfile\"; ");
sprintf(pre + strlen(pre), "filename=\"%s\"\r\n", filename);
sprintf(pre + strlen(pre), "Content-Type: application/octet-stream\r\n");
sprintf(pre + strlen(pre), "Content-Transfer-Encoding: binary\r\n\r\n");
sprintf(post, "\r\n--%s--\r\n", boundary);
int filesize = get_filesize(filename);
int length = filesize + strlen(pre) + strlen(post);
sprintf(header, "POST /test/upload.php HTTP/1.0\r\n");
sprintf(header + strlen(header), "Host: %s\r\n", hostname);
sprintf(header + strlen(header), "Content-Type:multipart/form-data; ");
sprintf(header + strlen(header), "boundary=%s\r\n", boundary);
sprintf(header + strlen(header), "Content-Length: %d\r\n\r\n", length);
write(sock, header, strlen(header));
write(sock, pre, strlen(pre));
send_file(sock, filename);
write(sock, post, strlen(post));
while(1){
char buf[1024];
int size = read(sock, buf, sizeof(buf));
if(size <= 0){
break;
}
buf[size] = 0;
printf(">> %s\n", buf);
}
close(sock);
}
テスト用コード †ファイルを受信して保存するPHP: upload.php †<?php $uploaddir = './'; print_r($_FILES); $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile); ?> ファイル送信フォーム: form.html †<form enctype="multipart/form-data" action="upload.php" method="POST"> upload file: <input name="userfile" type="file" /> <input type="submit" value="send" /> </form> |