어플리케이션에서 파일 업로드 하는 방법을 구현해 보자
파일과 폼데이타를 같이 보내보자
서버단은 닷넷 프레임워크에 있으니 어렵지 않게 구현이 가능할 것인다.
실제 업로드 사용중 모듈에서 빼서 가져왔다.
약간의 에러가 있을지 모르겠다.
공부한다 생각하고 나머지는 찾아보는게 좋을것 같다.
string dataBoundary = Guid.NewGuid().ToString();
FileInfo fileInfo = new FileInfo(arrFullFileName[i].ToString());
FileStream fs = new FileStream(arrFullFileName[i].ToString(), FileMode.Open, FileAccess.Read);
long currSizeForThisFile = 0;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(urlPath);
webRequest.UserAgent = "fileUpload";
webRequest.ContentType = "multipart/form-data; boundary=" + dataBoundary;
webRequest.Method = "POST";
webRequest.KeepAlive = true;
string headerStr = String.Format(
"--{0}\r\n"
+ "Content-Disposition: form-data; name=\"File1\"; filename=\"{1}\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "\r\n",
dataBoundary, fileInfo.Name);
StringBuilder postParam = new StringBuilder();
postParam.AppendFormat("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", dataBoundary, "index", (i+1).ToString());
postParam.AppendFormat("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", dataBoundary, "file_path", arrFullFilePath[i]);
postParam.AppendFormat("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", dataBoundary, "file_size", fileInfo.Length.ToString());
postParam.Append(headerStr);
//Encoding encoding = Encoding.UTF8;
//postResult = encoding.GetBytes(postParam.ToString());
byte[] headerBytes = Encoding.Default.GetBytes(postParam.ToString());
//byte[] headerBytes = Encoding.Default.GetBytes(headerStr);
//string trailerStr = String.Format("--{0}--\r\n", dataBoundary);
string trailerStr = String.Format("\r\n--{0}\r\n", dataBoundary);
byte[] trailerBytes = Encoding.Default.GetBytes(trailerStr);
webRequest.ContentLength = headerBytes.Length + trailerBytes.Length + fileInfo.Length;
Stream webStream = webRequest.GetRequestStream();
// write the header to the web stream
webStream.Write(headerBytes, 0, headerBytes.Length);
//webStream.Write(postResult, headerBytes.Length, postResult.Length);
// write the file to the stream
byte[] buffer = new byte[1024 * 10];
const int LENGTH = 1024;
const int OFFSET = 0;
int rcvd = 0;
do
{
rcvd = fs.Read(buffer, OFFSET, LENGTH);
if (rcvd > 0 && !enableExit)
{
webStream.Write(buffer, 0, rcvd);
currSize += rcvd;
currSizeForThisFile += rcvd;
this.SetStatus(i + 1, this.arrFullFileName.Length, currSize, currSizeForThisFile, this.totalSize, arrFileSize[i], fileInfo.Name);
}
} while (rcvd > 0);
webStream.Write(trailerBytes, 0, trailerBytes.Length);
using (StreamReader sr = new StreamReader(((HttpWebResponse)webRequest.GetResponse()).GetResponseStream()))
{
strUPloadReturnXml = sr.ReadToEnd();
}
System.Threading.Thread.Sleep(50);
fs.Close();
webStream.Close();