프로그램적으로 파일업로드

-- C# 2012. 11. 23. 14:36
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
파일업로드를 하려면 와 같이 테그를 이용하여 업로드 할 수 있는데, 파일명이 주기적으로 바뀌고 매일 업로드를 해야한다면 페이지를 이용하여 작업하기란 너무 번거로운 일이다. 그래서 이 업로드 작업을 프로그램으로 자동적으로 하는 것이 필요하다.

protected static void FileUpload()
{
string strURL = "http://www.remoteserver.com/upload.aspx";
string strParam = "param1=p1&m2=p2";
string strFilePath = "c:\\test.txt";

string strResult = HttpFileUpload(strURL, strParam, strFilePath);
}

static string HttpFileUpload(string strURL, string strParam, string strFilePath)
{
string strBoundary = "-----------------------------7dc298630874"; // 구분자

Dictionary dicParams = new Dictionary();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURL);

req.AllowAutoRedirect = true;
req.AllowWriteStreamBuffering = true;
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + strBoundary;

if(!string.IsNullOrEmpty(strParam))
{
foreach (string param in strParam.Split('&'))
{
string strName = param.Split('=')[0];
string strValue = param.Split('=')[1];

dicParams.Add(strName, strValue);
}
}

FileStream fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[1024]; 

int nRead = fs.Read(bytes, 0, bytes.Length);
fs.Close();

dicParams.Add("filename", new FileParamFormat(bytes, strFilePath, "text/plain"));
byte[] buffer = GetMultipartFormData(Encoding.GetEncoding("gb2312"), dicParams, strBoundary);

int bufferLength = buffer.Length;
req.ContentLength = bufferLength;

// Request
Stream reqStream = req.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

HttpWebResponse res = (HttpWebResponse)req.GetResponse();

// Response
Stream resStream = res.GetResponseStream();
StreamReader resReader = new StreamReader(resStream, Encoding.GetEncoding("gb2312"));
string strResult = resReader.ReadToEnd();
resStream.Close();
res.Close();

return strResult;
}

public class FileParamFormat 
{
public byte[] File { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public FileParamFormat (byte[] file) : this(file, null) { }
public FileParamFormat (byte[] file, string filename) : this(file, filename, null) { }

public FileParamFormat (byte[] file, string filename, string contenttype)
{
File = file;
FileName = filename;
ContentType = contenttype;
}
}

static byte[] GetMultipartFormData(Encoding encoding, Dictionary dicParams, string strBoundary)
{
Stream stream = new System.IO.MemoryStream();

foreach (var param in dicParams)
{
if (param.Value is FileParamFormat)
{
// file parameter
FileParamFormat fileParam = (FileParamFormat)param.Value;

string strHeader = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
strBoundary,
param.Key,
fileParam.FileName ?? param.Key,
fileParam.ContentType ?? "application/octet-stream");

stream.Write(encoding.GetBytes(strHeader), 0, strHeader.Length);
stream.Write(fileParam.File, 0, fileParam.File.Length);
}
else
{
// text parameter
string strParam = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
strBoundary,
param.Key,
param.Value);

stream.Write(encoding.GetBytes(strParam), 0, strParam.Length);
}
}

string strFooter = "--" + strBoundary + "--\r\n";
stream.Write(encoding.GetBytes(strFooter), 0, strFooter.Length);
stream.Position = 0;

byte[] formData = new byte[stream.Length];
stream.Read(formData, 0, formData.Length);
stream.Close();

return formData;
}
posted by 어린왕자악꿍