Usuário com melhor resposta
Ao Abrir documentos para download Office 2007(docx,xlsx,...) abrem como arquivo corrompido C#

Pergunta
-
Bom dia a todos estou fazendo uma aplicação de chamados em C# onde os chamados podem conter anexos, eu montei uma pagina para mostrar o chamado ao usuario mostrando os anexos que ele postou onde o link de cada um redireciona para minha pagina ExibirAnexo.aspx onde eu pego o Id do Anexo e abro pro usuario fazer download até ae blza, mas quando eu posto um arquivo docx ou xlsx ele abre como arquivo corrompido.
No banco de dados do Anexo estou salvando o nome do arquivo,extensão e o arquivo (campo Varbinary(max)), nas outras extensoes como .doc .xls o arquivo abre sem nenhum problema tentei mudar o ContentType inúmeras vezes mais nenhuma deu certo.
ExibirAnexo.aspx.cs
+--------------------------------------------
using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using SED.DAO.PortalSistemasDAO;using SED.DCL;using SED.UTIL;using System.IO;using System.Data.Linq;namespace PortalSistemas.APW.Solicitacoes{public partial class ExibirAnexo : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){int AnexoID = 0;if (!int.TryParse(Request.QueryString["id"].ToString(), out AnexoID))throw new Exception("O código do Anexo não foi Informado!");PortalAnexo anexo = new PortalAnexoDAO().Obter(AnexoID);Response.ClearHeaders();Response.Clear();Response.ContentEncoding = System.Text.Encoding.UTF8;switch (anexo.Extensao){case ".doc":Response.ContentType = "application/msword";Response.AddHeader("content-disposition", "attachment;filename=" + anexo.NomeArquivo);break;case ".docx":Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";Response.AddHeader("content-disposition", "attachment;filename=" + anexo.NomeArquivo);break;case ".xls":Response.ContentType = "application/vnd.ms-excel";Response.AddHeader("content-disposition", "attachment;filename=" + anexo.NomeArquivo);break;case ".xlsx":Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";Response.AddHeader("content-disposition", "attachment;filename=" +anexo.NomeArquivo);break;default:Response.ContentType = anexo.Extensao.ToString();Response.AddHeader("Content-Disposition", "attachment;filename=" + anexo.NomeArquivo);break;}Response.BinaryWrite((byte[])anexo.Arquivo.ToArray());HttpContext.Current.ApplicationInstance.CompleteRequest();Response.End();}}}
Respostas
-
Pessoal realmente suspeitei desde o principio, o problema estava sendo ao salvar o documento no Banco de Dados eu segui esse tutorial
http://www.codeguru.com/csharp/.net/net_asp/miscellaneous/print.php/c15417
Na hora de salvar coloquei esse codigo e deu certo na hora de chamar os arquivos
+---------------------------------------------------------------------+
Stream stream = flpArquivo.PostedFile.InputStream;
int length = flpArquivo.PostedFile.ContentLength;
byte[] data = new byte[length];int n = stream.Read(data, 0, length);
anexo.Arquivo = data;+---------------------------------------------------------------------+
- Marcado como Resposta Anderson segunda-feira, 19 de dezembro de 2011 12:23
Todas as Respostas
-
Anderson, boa tarde. Segue exemplo:
case "DOC", "DOCX": { HttpContext.Current.Response.ContentType = "APPLICATION/MSWORD"; } case "XLS", "XLSX": { HttpContext.Current.Response.ContentType = "APPLICATION/MS-EXCEL"; }
Atenciosamente,Onofre A. Juvencio Junior(Se a achou útil o post, por favor, marque-o como resposta) -
-
Anderson, boa tarde. veja o método que eu utilizo, é exatamente o que você precisa:
public static void GerarArquivo(byte[] _Arquivo) { byte[] btArquivo = _Arquivo; try { string[] strInfoArquivo = null; string strExtensaoArquivo = null; string strNomeArquivo = null; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("Content-Length", btArquivo.Length.ToString()); switch (strExtensaoArquivo.ToUpper()) { case "BMP": { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "IMAGE/BMP"; break; } case "JPEG": { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "IMAGE/JPEG"; break; } case "JPG": { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "IMAGE/JPEG"; break; } case "GIF": { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "IMAGE/GIF"; break; } case "PDF": { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "APPLICATION/PDF"; break; } case "DOC": { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "APPLICATION/MSWORD"; break; } case "DOCX": { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "APPLICATION/MSWORD"; break; } case "XLS": { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "APPLICATION/MS-EXCEL"; break; } case "XLSX": { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "APPLICATION/MS-EXCEL"; break; } default: { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strNomeArquivo); HttpContext.Current.Response.ContentType = "APPLICATION/X-MSDOWNLOAD"; break; } } } catch (Exception _excpErro) { btArquivo = Encoding.Default.GetBytes(String.Format("{0}: ocorreu o seguinte erro ao gerar o arquivo - {1}", MethodInfo.GetCurrentMethod().Name, _excpErro.Message)); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "TEXT/TXT"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=ERRO.txt"); } finally { HttpContext.Current.Response.BinaryWrite(btArquivo); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Close(); } }
Atenciosamente,
Onofre A. Juvencio Junior
(Se a achou útil o post, por favor, marque-o como resposta)
- Editado Onofre Antonio Juvencio Jr quinta-feira, 15 de dezembro de 2011 19:10
-
Onofre fiz conforme seu codigo porém o resultado foi o mesmo ao abrir o documento conforme o post anterior que eu mandei o print to mandando o codigo que eu fiz:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using SED.DAO.PortalSistemasDAO;
using SED.DCL;
using SED.UTIL;
namespace PortalSistemas.APW.Solicitacoes
{
public partial class Anexo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int AnexoID = 0;
if (!int.TryParse(Request.QueryString["id"].ToString(), out AnexoID))
throw new Exception("O código do Anexo não foi Informado!");
PortalAnexo anexo = new PortalAnexoDAO().Obter(AnexoID);
GerarArquivo(anexo.Arquivo.ToArray(), anexo.NomeArquivo, anexo.Extensao);
}
public static void GerarArquivo(byte[] _Arquivo,String nomeArq,String Extensao)
{
byte[] btArquivo = _Arquivo;
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Length", btArquivo.Length.ToString());
switch (Extensao.ToUpper())
{
case "BMP":
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "IMAGE/BMP";
break;
}
case "JPEG":
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "IMAGE/JPEG";
break;
}
case "JPG":
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "IMAGE/JPEG";
break;
}
case "GIF":
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "IMAGE/GIF";
break;
}
case "PDF":
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "APPLICATION/PDF";
break;
}
case "DOC":
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "APPLICATION/MSWORD";
break;
}
case "DOCX":
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "APPLICATION/MSWORD";
break;
}
case "XLS":
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "APPLICATION/MS-EXCEL";
break;
}
case "XLSX":
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "APPLICATION/MS-EXCEL";
break;
}
default:
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + nomeArq);
HttpContext.Current.Response.ContentType = "APPLICATION/X-MSDOWNLOAD";
break;
}
}
}
catch (Exception _excpErro)
{
btArquivo = System.Text.Encoding.Default.GetBytes(String.Format("{0}: ocorreu o seguinte erro ao gerar o arquivo - {1}", System.Reflection.MethodInfo.GetCurrentMethod().Name, _excpErro.Message));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "TEXT/TXT";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=ERRO.txt");
}
finally
{
HttpContext.Current.Response.BinaryWrite(btArquivo);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
}
}
}
}
-
O problema pode ser também quando eu to salvando os docx no banco ele pode está corrompendo nesse ponto to mandando meu arquivo de inserir:
protected void btnSalvar_Click(object sender, ImageClickEventArgs e)
{
try
{
PortalSolicitacoe solicitacao = new PortalSolicitacoe();
solicitacao.DataSolicitacao = DateTime.Now;
solicitacao.SistemaID = Convert.ToInt32(ddlSistema.SelectedValue);
solicitacao.Assunto = txtAssunto.Text;
solicitacao.Descricao = txtDescricao.Text;
solicitacao.UnidadeEscolarID = Convert.ToInt32(ddlUnidadeEscolar.SelectedValue);
solicitacao.NomeSolicitante = txtUsuarioSolicitante.Text;
solicitacao.UsuarioID = Convert.ToInt32(Session["UsuarioID"]);
solicitacao.Telefone = txtTelefone.Text;
solicitacao.Celular = txtCelular.Text;
solicitacao.Email = txtEmail.Text;
solicitacao.StatusID = 1;//Aberto
solicitacao.ValidarInserir();
new PortalSolicitacoesDAO().Inserir(solicitacao);
if (flpArquivo1.HasFile)
{
byte[] arquivoBytes1 = new byte[flpArquivo1.PostedFile.InputStream.Length + 1];
flpArquivo1.PostedFile.InputStream.Read(arquivoBytes1, 0, arquivoBytes1.Length);
PortalAnexo anexo1 = new PortalAnexo();
anexo1.NomeArquivo = Path.GetFileName(flpArquivo1.PostedFile.FileName).ToLower();
anexo1.Extensao = Path.GetExtension(flpArquivo1.PostedFile.FileName).ToLower();
anexo1.Arquivo = new Binary(arquivoBytes1);
anexo1.SolicitacaoID = solicitacao.SolicitacaoID;
new PortalAnexoDAO().Inserir(anexo1);
}
} catch (Exception ex)
{
Master.RetornarMensagem(ex.Message,true);
}}
-
Pessoal realmente suspeitei desde o principio, o problema estava sendo ao salvar o documento no Banco de Dados eu segui esse tutorial
http://www.codeguru.com/csharp/.net/net_asp/miscellaneous/print.php/c15417
Na hora de salvar coloquei esse codigo e deu certo na hora de chamar os arquivos
+---------------------------------------------------------------------+
Stream stream = flpArquivo.PostedFile.InputStream;
int length = flpArquivo.PostedFile.ContentLength;
byte[] data = new byte[length];int n = stream.Read(data, 0, length);
anexo.Arquivo = data;+---------------------------------------------------------------------+
- Marcado como Resposta Anderson segunda-feira, 19 de dezembro de 2011 12:23