Codificando .Net

Aprendizado, companherismo, ensino e aperfeiçoamento constante

Neste artigo, irei apresentar como é implementado o upload de arquivos no Asp.Net 2.0 utilizando o Visual Studio 2005 ou Web Developer de mesma versão. Os mesmo recursos podem ser usados na versão 2008.

Para começar, vamos criar um WEB Site no Visual Studio 2005. Para isso clique em File –> New Site. Salve com o nome Upload no local desejado.

Automaticamente será acrescentado um WebForm de nome Default.aspx. No modo Design, acrescente os seguintes controles: 1 FileUpload, 1 Button e 1 Label.

Altera as propriedades dos controles de acordo com as instruções abaixo:
Button: ID = “btnSalvar” e Text=”Salvar”
Label: ID = “Label” e Text=”Label”

Dê um duplo clique no Button e acrescente o seguinte código:

if (FileUpload1.HasFile)
{
try
{
FileUpload1.SaveAs("Caminho" + FileUpload1.FileName);
Label.Text = string.Format("File: {0} {1} kb - Content Type {2} ",
FileUpload1.PostedFile.FileName, FileUpload1.PostedFile.ContentLength,
FileUpload1.PostedFile.ContentType);
}
catch (Exception ex)
{
Label.Text = "ERRO: " + ex.Message.ToString();
}
}
else
{
Label.Text = "Você deve escolher um arquivo para o upload.";
}

Entendendo o Código:

A linha do comando

if (FileUpload1.HasFile)

verifica se foi enviado algum arquivo. Caso esta condição seja satisfeita, o arquivo é salvo através do método

FileUpload1.SaveAs("Caminho" + FileUpload1.FileName);

e é exibida uma mensagem ao usuário informando o nome, tamanho e tipo do arquivo. Caso contrário, será exibida uma mensagem informando que nenhum arquivo foi selecionado. A string “Caminho”, deverá ser substituída pelo local onde o arquivo deverá ser salvo. Ex.: “C:\\Temp\\”

Com o uso dos elementos try e catch podemos capturar qualquer erro que ocorra durante a operação, e caso ocorra algum erro ele é exibido ao usuário

Label.Text = "ERRO: " + ex.Message.ToString();

Um erro comum em aplicações com upload é a falta de permissão de escrita na pasta onde será gravado o arquivo, verifique se a pasta que pretende fazer o upload possui permissão de escrita.

Um grande abraço e até o próximo artigo.
Márcio Assis Miranda

Exibições: 7424

Tags: Asp.Net, C#, Upload

Comentário de André Gusmão em 21 janeiro 2009 às 12:04
Márcio, muito bom seu post, bem explicativo.
Gostaria de acrescentar mais uma coisa a ele que seria como fazer upload de arquivo para uma tabela de um banco de dados:

Basta ter uma tabela com uma coluna do tipo Image (SQL Server) ou BLOB (Oracle).
Para que possa ser gravado o arquivo binário na tabela é necessário primeiro transformá-lo em uma sequência de bytes, da seguinte forma:

string FileName = FileUpload1.PostedFile.FileName;
int FileSize = Convert.ToInt32(FileUpload1.PostedFile.InputStream.Length);
byte[] buffer = new byte[FileSize];
FileUpload1.PostedFile.InputStream.Read(buffer, 0, FileSize);

Pronto, agora a variável buffer contem um array de bytes com o conteúdo do arquivo do upload.
Agora basta gravá-lo diretamente no banco de dados, como nesse exemplo em LINQ:

MinhaTabela tbl = new MinhaTabela { campo_arquivo = buffer };
db.MinhaTabela.InsertOnSubmit(tbl);
db.SubmitChanges();
Comentário de Márcio Assis Miranda em 21 janeiro 2009 às 13:45
André, valeu pela dica.
É isso aí, agora sim ficou completíssimo.
Muitíssimo obrigado!
Comentário de Marcus Vinicius em 13 abril 2009 às 10:52
Blz Márcio,
Como poderia fazer um upload estilo FTP?
Por que tenho uma página web e gostaria que o usuário envia-se um arquivo para minha pasta especifica no servidor locaweb!! como poderia ser feito isso?
Conto com sua ajuda!!! :)
Comentário de Neida Oliva em 7 maio 2009 às 9:27
Queria que ao fazer o upload notificasse duas pessoas por email que tal arquivo foi carregado.
Comentário de MariamWilson em 22 novembro 2012 às 8:36
Here's a conclusion of five sound advice you can use, and you're not alone in this... keep in mind if you need anything, come join us at PhenForum.com for assistance.

1. Because Apettite supressants takes away your craving for food and urges, you can reduce your calorie consumption by consuming more plant meals and trim meats; and consuming meals in smaller ratios.

2. Create a shopping list and pick out healthier ingredients for your own meals, especially if your family doesn't eat sensibly.

3. Eat sharp, fresh and vibrant vegetables; and trim necessary protein like fish and chopped up poultry, trying to stability each food out so you have say...

a. 30% unsaturated fat

b. 30% protein

c. 40% carbohydrates

4. Limit how much you eat (but DO NOT come close to hungry yourself). Think of your system as a machine that only operates properly if you put the right stability and quantity of nutritional value in it.

When we take Apettite supressants, it can be hard to eat more than a piece of make and a food tremble in one day. Because Apettite supressants prevents you from feeling hungry at all, you have no desire to eat, and sometimes meals can even seem total. Do not view this as a best part, though. To shed bodyweight completely, you'll have to fight to eat!

Now your concern will be for making sure you eat often enough to keep your system healthier and keep your metabolic rate high. If you don't eat enough, you will destroy your reducing bodyweight because as soon as you quit taking Apettite supressants and begin to eat more food again, you'll obtain a lot of bodyweight back because your human is in craving for food method. In craving for food method, your metabolic rate is very low, and your system will instantly store most of your calorie consumption as fat.

So keep in mind, the more meals, the higher the metabolic rate. Try not to let your system go hungry. You should eat around 4-5 times a day - not large meals but mid-sized meals and a couple of treats. Three rectangle meals are just too much of a whirlwind drive for the system. Carbohydrate food are most important to eat in the morning and need you'll need to eat less and less carbohydrates up to bed time.

Also, don't worry about consuming before bed. Your human demands a certain variety of calorie consumption which can be calculated online and if your system has not met that variety for the day, then you are still fine.

What's a excellent meal?

You should be consuming anything from a poultry food on whole feed with an apple and peanuts to a cooked poultry healthy salad with different kinds of lettuce or fresh vegetables in the mix. Meals like that are efficient ways to educate your system to love proper nourishment.phen375 Fat Burner


http://www.healthproductportal.com/2012/08/phen375-reviews.html

phen375

[url=http://www.phen375information.com]http://www.phen375information.com[/url]

[url=http://www.healthproductportal.com/2012/08/phen375-reviews.html]phen375 supplements[/url]

So every 3-4 hours you'll be consuming a excellent, trim source of necessary protein with some whole grains.

Ian Robertson, CPT is a qualified instructor with over 5 years of experience in reducing bodyweight and fitness. As the formal instructor and reducing bodyweight expert at PhenForum.com, he helps members shed bodyweight quicker and keep it off. PhenForum is the only assistance group on the internet that offers a Weight Reduction Program specially for Apettite supressants users. It's all about losing bodyweight, AND keeping it off permanently instead of suffering from recovery excess bodyweight. No more yo-yo-ing.
Comentário de MariamWilson em 13 dezembro 2012 às 4:06

Acai Berry Scam Part 4
FREE TRIALS

This is probably the most highly debated aspect of acai fresh fruits and veggies controversy. If you are not familiar with these promotions, generally what happens is a company gives away a test provide of a given complement. It is usually decreasing bodyweight related, but I have seen them for everything from Dr. Suess books to teeth whitening treatments. The aspect is, you have to pay for shipping and handling which is usually around $5 or so. What some people http://acaiberry.tripod.co.uk don't realize is that you are agreeing to a monthly auto-shipment unless or until you terminate. This can cause to unexpected supply and expenses on the credit card you used to pay for the shipping on the test provide.

Comentar

Você precisa ser um membro de Codificando .Net para adicionar comentários!

Entrar em Codificando .Net

Patrocínios

 

 

Comunidade Daruma 

Editora O'Reilly 

 

© 2013   Criado por Alexandre Tarifa.   Ativado por

Badges  |  Relatar um incidente  |  Termos de serviço