Contoh kode untuk mengirim file menggunakan HTTPWebReqeust. Jika bukan MVC, dapat meng-add Microsoft.Net.Http pada NuGet.
Kode di bagian pengiriman file
[code language=”csharp”]
public string HttpPost(string url, string fileName, byte[] fileByte, string username)
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
HttpContent fileNameContent = new StringContent(fileName);
HttpContent usernameContent = new StringContent(username == null ? "" : username);
HttpContent fileContent = new ByteArrayContent(fileByte);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
using (var client = new HttpClient())
{
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileNameContent, "fileName");
formData.Add(fileContent, "fileContent");
formData.Add(usernameContent, "username");
var response = client.PostAsync(url, formData).Result;
if (!response.IsSuccessStatusCode)
{
return null;
}
return response.Content.ReadAsStringAsync().Result;
}
}
}
[/code]
Kode di bagian Web API penerima file.
[code language=”csharp”]
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
//kamus
string root = HttpContext.Current.Server.MapPath("~/Uploads");
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root);
string username, fileName, friendlyFileNameOnly, fileNameOnly, fullPath, ext;
string savedFileName = null;
FileInfo fInfo;
int i;
//algoritma
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
try
{
await Request.Content.ReadAsMultipartAsync(provider);
username = provider.FormData.GetValues("username").First();
foreach (var fd in provider.FileData)
{
fInfo = new FileInfo(fd.LocalFileName); i = 0;
fileName = fd.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
fileNameOnly = Path.GetFileNameWithoutExtension(fileName);
friendlyFileNameOnly = new DisplayFormatHelper().URLFriendly(fileNameOnly);
ext = Path.GetExtension(fileName);
savedFileName = friendlyFileNameOnly + ext;
fullPath = Path.Combine(root, savedFileName);
while (File.Exists(fullPath))
{
savedFileName = friendlyFileNameOnly + "_" + i + ext;
fullPath = Path.Combine(root, savedFileName);
++i;
}
File.Move(fInfo.FullName, fullPath);
}
return Request.CreateResponse(HttpStatusCode.OK, savedFileName);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
private byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
[/code]
http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data