I am going to create a WebApi service called FileService that can be used to upload and download files. The service will only contain 2 methods. A Post to upload and a Get method that accepts an id parameter to identify the file that needs to be downloaded. Let’s start with the Post method.
The Post method
This method will look in the Request object to see if there are any posted files. If so, it will loop over the files and create them on the server side. The server will return a 201 HttpStatus and a list of strings that will contain the full path of the file(s) at server side. When there are no files posted, the service will return a 401 status a.k.a. BadRequest.
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count > 0)
{
var files = new List<string>();
// interate the files and save on the server
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs( filePath);
files.Add(filePath);
}
// return result
result = Request.CreateResponse(HttpStatusCode.Created, files);
}
else
{
// return BadRequest (no file(s) available)
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
The Get Method
As mentioned before, the Get Method will accept a string file that will identify (= filename) the file that needs to be downloaded.
public HttpResponseMessage Get(string id)
{
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath("~/" + id);
// check if parameter is valid
if (String.IsNullOrEmpty(id))
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
// check if file exists on the server
else if (!File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{// serve the file to the client
result = Request.CreateResponse( HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = id;
}
return result;
}
Uploading a File
Using a submit button
<form name="form1" method="post" action="api/file" enctype="multipart/form-data">
<div>
<label>
Using submit</label>
<input name="myFile" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
Using JQuery
<form enctype="multipart/form-data">
<label>
Using JQuery</label>
<input name="file" type="file" />
<input type="button" id="Upload" value="Upload" />
</form>
<script type="text/javascript">
$(function () {
$('#Upload').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: 'api/file',
type: 'POST',
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
});
});
</script>
Downloading a File
Summary
The solution can be downloaded here.
Thanks for share this code.
ReplyDeleteExcellent!
ReplyDeletethanx
ReplyDeleteThis is working excellent with Chrome & Firefox but not working with IE. Please Help me. Advance Thanks
ReplyDeleteHi, thanks a lot for this article, I want to ask you how can I use this code to upload file into dropbox, I've made registration for dropbox App. The problem is that my task is to upload the file with web service( ASP.NET WebAPI).
ReplyDeleteMy idea is to upload the file in dropbox, then return the link and record it in database in AppHarbor ?
Very nice documentation on uploading files, but none regarding downloading files. Could you pls add that to the content?
ReplyDeleteAt last full working demo. Everything else that I find today have a plenty of errors and not work. Thank you for you help.
ReplyDeleteWhat is the maximum length of the file that can be uploaded?
ReplyDeleteThanks
This Get method will only allow one file download at a time. Check out for Async: https://stackoverflow.com/questions/21533022/web-api-2-download-file-using-async-taskihttpactionresult
ReplyDeleteDoes it work for IE8?
ReplyDeleteHi nice article,this file uploading method with JQuery will help me. you should creat a best resume writing for a html developer job.
ReplyDeleteThank you! this help me much
ReplyDeletehttp://bongdago.com
Thanks for your share, by the way if I would like to have two block of file upload and how can we do to separate which one is belong to which file upload control?
ReplyDeleteBest regards,
Sokhawin
Excellent article shared excellent data on this topic. I will share this with you. If you want to know about the keyboard problem. You can follow this profile in the keyboard tester.
ReplyDeleteVan
ReplyDeleteizmir
Artvin
Tunceli
Eskişehir
1UUİJC
yozgat
ReplyDeletetunceli
hakkari
zonguldak
adıyaman
43TSDK
whatsapp görüntülü show
ReplyDeleteücretli.show
AJU
C5ED8
ReplyDeleteSinop Lojistik
Urfa Lojistik
Denizli Evden Eve Nakliyat
Antalya Lojistik
Isparta Evden Eve Nakliyat
9E3E5
ReplyDeleteAmasya Şehir İçi Nakliyat
Çerkezköy Koltuk Kaplama
Erzurum Şehir İçi Nakliyat
Yozgat Lojistik
Maraş Parça Eşya Taşıma
Balıkesir Evden Eve Nakliyat
Ardahan Lojistik
Çorum Parça Eşya Taşıma
Denizli Evden Eve Nakliyat
0C69E
ReplyDeleteAydın Evden Eve Nakliyat
Osmaniye Parça Eşya Taşıma
Sonm Coin Hangi Borsada
Maraş Lojistik
Afyon Evden Eve Nakliyat
Urfa Şehir İçi Nakliyat
Referans Kimliği Nedir
Kars Şehirler Arası Nakliyat
Big Wolf Coin Hangi Borsada
F4228
ReplyDeleteÇerkezköy Çelik Kapı
Star Atlas Coin Hangi Borsada
Ankara Boya Ustası
Kayseri Evden Eve Nakliyat
Bartın Şehir İçi Nakliyat
Şırnak Evden Eve Nakliyat
Adana Şehir İçi Nakliyat
Çerkezköy Buzdolabı Tamircisi
Silivri Evden Eve Nakliyat
3FAD6
ReplyDeleteCoin Kazma Siteleri
Bitcoin Nasıl Üretilir
Kripto Para Oynama
Coin Nasıl Çıkarılır
magnet
Bitcoin Madenciliği Siteleri
Coin Çıkarma
Binance Neden Tercih Edilir
Bitcoin Nasıl Oynanır
319AC
ReplyDeleteşırnak sesli sohbet siteleri
telefonda görüntülü sohbet
niğde bedava sohbet
kırklareli mobil sohbet bedava
gümüşhane bedava sohbet odaları
adıyaman seslı sohbet sıtelerı
ağrı kızlarla rastgele sohbet
balıkesir bedava sohbet odaları
telefonda kadınlarla sohbet
17209
ReplyDeletekızlarla rastgele sohbet
rize en iyi görüntülü sohbet uygulaması
antalya canlı sohbet bedava
bedava görüntülü sohbet
kayseri bedava sohbet chat odaları
canli sohbet bedava
yalova görüntülü sohbet kadınlarla
mardin rastgele görüntülü sohbet uygulamaları
siirt mobil sohbet siteleri
1CCF3
ReplyDeleteTumblr Beğeni Hilesi
Trovo Takipçi Satın Al
Likee App Beğeni Hilesi
Bitcoin Kazma Siteleri
Görüntülü Sohbet Parasız
Parasız Görüntülü Sohbet
Hamster Coin Hangi Borsada
Okex Borsası Güvenilir mi
Pi Network Coin Hangi Borsada
Procurando uma alternativa ao WhatsApp com vantagens extras? GB WhatsApp é o seu mod preferido com mais privacidade, controle e talento para seus bate-papos. Aproveite os recursos inovadores e a personalização do
ReplyDeleteTrava Zap