Upload com ASP.NET MVC e jQuery

Já havia recebido 3 e-mails com dúvidas de como fazer upload no ASP.NET MVC e hoje me chamaram no  messenger com a mesma dúvida, então decidi escrever um post de como fazer isso de forma simples e bonita, é claro que vou usar o jQuery para isso.

No Web Form tínhamos um controle server side chamado FileUpload e no ASP.NET MVC não existe este controle, então temos que escrever o HTML necessário para fazer o formulário da forma correta, eu estou usando o plugin uploadify que faz o envio assíncrono de arquivos para o servidor, ele é muito flexível, mas irei mostrar somente o básico dele.

A primeira coisa a saber é que para enviar um arquivo para o server é necessário que o formulário contenha o parâmetro enctype configurado para "multipart/form-data", sem isso ele não vai conseguir enviar o arquivo, vejam o código HTML abaixo:

<h2>Upload</h2>
<% using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
    <fieldset>
    <label for="photo">Insira a sua foto:</label><input type="file" id="photo" name="photo" /><br />
    <input type="submit" value="Enviar" />
    </fieldset>
<%} %>

Agora  faça o download do plugin uploadify, copie os arquivos jquery.uploadify.v2.1.0.min.js e swfobject.js para a pasta Scripts, copie também os arquivos cancel.png, uploadify.css e uploadify.swf para a pasta Content.

Crie uma pasta com o nome de files na raiz da aplicação, é nesta pasta que será salvo os arquivos enviados.

Inclua o código JavaScript na MasterPage Site.Master (este é apenas um exemplo, eu prefiro colocar este javascript na View):

<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<link href="../../Content/uploadify.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/swfobject.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('#photo').uploadify({
            'uploader': '/content/uploadify.swf',
            'script': '<%=Url.Action("Upload","Home") %>',
            'cancelImg': '/content/cancel.png',
            'fileDesc':'Aruivos de Imagem',
            'fileExt': '*.jpg;*.gif',
            'sizeLimit':'4000000',
            auto:true
        });
    });
</script>

No código acima eu estou configurando o endereço de onde estão os arquivos necessários para o plugin, defino o caminho da action que irá receber o arquivo, o tamanho máximo do arquivo, habilitei a opção auto que automaticamente irá enviar o arquivo após a seleção do mesmo e também defino a extensão permitida para fazer o upload, isso é bem interessante porque na caixa de dialogo só irá aparecer os arquivos com a extensão que você definir.

Existem mais configurações que podem ser utilizadas, você pode conferir elas na documentação do plugin.

Agora só está faltando o código server side, eu criei uma action chamada upload no HomeController que irá receber e salvar o arquivo:

[AcceptVerbs(HttpVerbs.Post)]
public void Upload(string id)
{
    var file = this.Request.Files[0];
    string savedFileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files");
    savedFileName = System.IO.Path.Combine(savedFileName, System.IO.Path.GetFileName(file.FileName));
    file.SaveAs(savedFileName);
    Response.Write("OK");
}

Com isso você já terá funcionando o jQuery uploadify com o ASP.NET MVC, vejam como fica no final:

jquery_uploadfy_in_action

Baixe a solução completa.


Comments

Marcia receitinhas
Marcia receitinhas
21 September 2009 18:55
Não estou conseguindo baixar o arquivo, vai precisar da permissão na pasta  aonde vai gravar os arquivos?
Leandro Lemes
Leandro Lemes
5 October 2009 15:39
Parabéns pelo artigo. Estou aprendendo asp.net MVC, e estou precisando fazer uma aplicação que busque o arquivo, como listado no artigo, depois de fazer upload no arquivo, preciso tratar o arquivo(pegar alguns campos deste arquivo) e popular um BD. Você pode me ajudar a encontrar o caminho para fazer isso
Gustavo
Gustavo
30 December 2009 08:25
Mto bom post, parabens...
Luciano
Luciano
3 February 2010 10:53
Valeu, Victor!
Eu estava procurando uma solução legal para upload com MVC e acabei encontrando por acaso em seu blog.
love calculator
love calculator
17 February 2010 11:34
Hi, I was researching the net  and I came across your website. Keep up the great work.
Otis Corporal
Otis Corporal
17 February 2010 13:02
This is a very good piece of writing, I found your web site doing research google for a related topic and arrived to this. I couldnt get to much additional information and facts on this summary, so it was pleasant to discover this one. I will certainly end up being back to look at some other articles that you have another time.
computer printer ink
computer printer ink
17 February 2010 15:12

I would like to say that this blog really convinced me to do it! Thanks, very good post.

Thank you very much for that extraordinarily first class editorial!
computer projectors
computer projectors
18 February 2010 08:01
I would like to say that this blog really convinced me to do it! Thanks, very good post.
wheelchair lifts
wheelchair lifts
18 February 2010 08:02
Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post. Keep up your work.
Hai Tozzi
Hai Tozzi
18 February 2010 20:12
Terrific site, where did you come up with the knowledge in this piece? Im happy I found it though, ill be checking back soon to see what other articles you have.
Austin Naillon
Austin Naillon
19 February 2010 03:54
Hello, great day.. Your content is extremely uplifting. I never believed that it was feasible to do something like that until after I read your post. You undoubtedly offered an excellent understanding on how this kind of whole system operates. Ill make sure to visit for more tips. Keep it up!
Beau Ligonis
Beau Ligonis
19 February 2010 08:55
Very good site, where did you come up with the information in this article? Im happy I found it though, ill be checking back soon to see what other articles you have.
Riley Drzewicki
Riley Drzewicki
20 February 2010 00:23
Wonderful blog post, this is very similar to a site that I have. Please check it out sometime and feel free to leave me a comenet on it and tell me what you think. I'm always looking for feedback.
Ligia Thorpe
Ligia Thorpe
20 February 2010 09:58
I don't agree with everything in this summary, but you do make some very good points. I'm very interested in this subject and I myself do alot of research as well. Either way it was a well thoughtout and nice read so I figured I would leave you a comment. Feel free to check out my website sometime and let me know what you think.
Tess Mckearin
Tess Mckearin
20 February 2010 18:47
This is a terrific post, but I was wondering how do I suscribe to the RSS feed?
ehliyet
ehliyet
20 February 2010 22:26
I really enjoyed read your article, very interesting ...
Lakita Marusiak
Lakita Marusiak
21 February 2010 21:12
This is a good post, I was wondering if I could use this blog on my website, I will link it back to your website though. If this is a problem please let me know and I will take it down right away.
Nicolette Howk
Nicolette Howk
22 February 2010 10:07
Superb site, where did you come up with the knowledge in this piece of writing? Im happy I found it though, ill be checking back soon to see what other articles you have.
watch the pacific online
watch the pacific online
23 February 2010 16:51
Sorry if my english is not very good. i just intend to tell i like this article very much. say thank you
Izdelava internetnih strani
Izdelava internetnih strani
24 February 2010 07:45
Just wanted to tell you that your website is not showing up properly on the Opera.  Anyway, I have subscribed to your RSS feed. =)
jasmin live
jasmin live
24 February 2010 13:07
I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.
Boot Huren Amsterdam
Boot Huren Amsterdam
24 February 2010 14:41
This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It is the old what goes around comes around routine. Did you acquired lots of links and I see lots of trackbacks??
skate 3 Release
skate 3 Release
24 February 2010 15:37
<A href="http://skate3.de/demo/">Skate 3 Demo</A>
Laura Lokker
Laura Lokker
24 February 2010 23:49
This is a very intriguing post, I was looking for this knowledge. Just so you know I located your webpage when I was doing research for blogs like mine, so please check out my site sometime and leave me a comment to let me know what you think.
Chet Diggins
Chet Diggins
25 February 2010 10:10
Im glad I discovered this web page, I couldnt get any info on this matter prior to. Also operate a website and if you are ever interested in a little bit of visitor writing for me you should feel free to let me know, im always look for people to check out my weblog. Please stop by and leave a comment sometime!
Elvis Schwemmer
Elvis Schwemmer
25 February 2010 20:39
I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites blog site list and will be checking back soon. Please check out my site as well and let me know what you think.
casino
casino
25 February 2010 23:29
I don't know why but my browser doesn't show this page correctly...That said,&nbsp;it was a very interesting read, keep up the good work&nbsp;and I'll come back for more Smile
Erich Wartenberg
Erich Wartenberg
26 February 2010 06:37
Great site, where did you come up with the knowledge in this blog? Im happy I found it though, ill be checking back soon to see what other articles you have.
Fatcow Review
Fatcow Review
28 February 2010 16:54
Should I get a Dedicated Hosting? At the moment I am using fatcow but they keep disabling my account because of high server load. Im getting about 2,000 UV a day. What hosting should I get?
Britt M Borden
Britt M Borden
28 February 2010 18:48
You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!
Google optimizacija
Google optimizacija
1 March 2010 09:13
Thanks for this cool post.  i found your blog on google and find it is very useful.
Antone Asen
Antone Asen
1 March 2010 23:01
I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites web site list and will be checking back soon. Please check out my site as well and let me know what you think.
Skate 3 News
Skate 3 News
2 March 2010 09:03
As a Newbie, I am always searching online for articles that can help me. Thank you
escorts in london
escorts in london
2 March 2010 17:55
I enjoy your blog, couse I can read it from my Nokia.
Catarina Andresen
Catarina Andresen
2 March 2010 23:24
Delicious Blog...<a href=”www.jumbobay.com/.../list.htm”>Teak Furniture</a> I hope you have a  day!
Skate 3 Videos
Skate 3 Videos
3 March 2010 00:46
Blogroll links aint that great Tong but i am not the admin… Tong … Just Telling Tong
wow mobiles
wow mobiles
3 March 2010 02:48
WoW Mobile is awesome! I get free mobile service with t-mobile because I refered 3 people to wow. You can too!
beautyhealthperfume
beautyhealthperfume
3 March 2010 10:15
keep up the great work
watch movies online
watch movies online
3 March 2010 11:43
I like watching movies online, it is way easier than going to the theaters.
beach decor
beach decor
3 March 2010 16:23
I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.
beautyhealthperfume
beautyhealthperfume
3 March 2010 21:50
thanks for the information
<http//www.beautyhealthperfume.co.uk>
catalina foothills car title loan
I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post
watch movies online free
watch movies online free
4 March 2010 04:04
I enjoy watching movies online, it is way easier than going to the theaters.
Jamel Wasmus
Jamel Wasmus
5 March 2010 03:48
For some reason only half of the post is being displayed, is it my browser or the site?
WoW Mobile
WoW Mobile
5 March 2010 11:53
Is tethering against the TOS of cell phone providers? Which ones allow it?
boards
boards
6 March 2010 13:07
I have been surfing online more than three hours today, yet I never found any interesting article like yours. It's pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the internet will be much more useful than ever before.
tradesmart university
tradesmart university
9 March 2010 02:07
Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.
Mccarthy23Allison
Mccarthy23Allison
10 March 2010 01:10
Have no money to buy a house? Do not worry, because that's available to get the <a href="lowest-rate-loans.com">loans</a> to work out such problems. Hence get a short term loan to buy everything you need.
Bob McEwen
Bob McEwen
10 March 2010 11:14
amazing stuff thanx <a href=http://www.antiquesauctionstore.com>Click Here</a>
registry cleaner
registry cleaner
10 March 2010 15:57
Hello,I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.
oregon bankruptcy lawyer
oregon bankruptcy lawyer
10 March 2010 21:06
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.
dui attorney oregon
dui attorney oregon
10 March 2010 21:53
The beauty of these blogging engines and CMS platforms is the lack of limitations and ease of manipulation that allows developers to implement rich content and 'skin' the site in such a way that with very little effort one would never notice what it is making the site tick all without limiting content and effectiveness.

Add comment


(Will show your Gravatar icon)

biuquote
Loading