// File Upload Example # 2
// by Matt Flood
// Copyright 2002, 2003
//
// this CGI script prompts the user to upload a file
// When submitted, the program returns the users file in a new window.
// The file should not be corrupted by the upload or download.
//

#include <rude/cgiparser.h>
#include <iostream>
#include <stdio.h>

int main(void)
{

	// 
	//
	std::cout << "Content-Type: text/html\n\n";

	
	// obtain the global CGI Parser object
	//
	rude::CGIParser parser;

	std::string message="";
	// Check if a file was uploaded - identified by "testfile"
	//
	if( parser.exists("testfile") && parser.isFile("testfile") )
	{
		// open file for binary write
		//
		FILE *handle = fopen(parser.filename("testfile"), "wb"); 

		if(handle)
		{
			fwrite(parser.value("testfile"), parser.length("testfile"));
			message = "Created file '"  << parser.filename("testfile") << "' for writing";
		}
		else
		{
			message = "Could not open file '" << parser.filename("testfile") << "' for writing";
		}

	}
	


	// Display a form for user to enter file into.  It is a recursive form that points back to this script - named example2.exe
	//
	std::cout << "<html><body>"
			<< message 
			<< "<br>"
			<< "<form action='example2.exe' method='POST' enctype='multipart/form-data' target='_new'>\n"
			<< "<input type=file name=testfile>\n"
			<< "<input type=submit value='upload testfile'>\n"
			<< "</form></body></html>\n";
	}
	return 0;
}

