所有类型的文件都应使用哪种内容类型在asp.net中下载文件? [英] Which content type should use for all types of files to download file in asp.net?

查看:60
本文介绍了所有类型的文件都应使用哪种内容类型在asp.net中下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有在asp.net中下载文件的功能.我有字节,文件名和大小.我已经尝试按照以下方式进行操作,但是每当我打开文件时,它都无法正确打开.如果是jpg或png文件,则不会显示图片.

I have functionality to download file in asp.net. I have bytes, filename and size. I have tried by following way but whenever I open file, it doesn't open correctly. If it's jpg or png file, it doesn't display picture.

这是我单击按钮时的代码:

Here is my code on button click:

byte[] bytes = Encoding.ASCII.GetBytes(getStringFromServer());
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();

我在某处阅读了需要指定ContentType的内容.但就我而言,文件可以是任何类型.

I have read somewhere that I need to specify ContentType. But in my case, file can be of any type.

有人可以指导我采取适当的方式吗?

Can anybody please guide me appropriate way?

推荐答案

内容类型的目的是允许用户代理(UA)确定下载资源的类型.没有内容类型,下载的内容就是裸数据,可以是任何内容.

The purpose of the content type is to allow the user agent (UA) to determine the type of the downloaded resource. Without a content type, the downloaded content is just naked data which could be anything.

在某些情况下可能会推断出内容类型,但这在很大程度上取决于上下文.如果内容是图像,则UA可以推断图像类型,如果内容是文本,则可以检查字节顺序标记等.但是由于数据几乎是任何东西,UA无法做到这一点推论.

It might be possible in some cases to infer the content type, but that is highly dependent on context. If the content is an image, the UA could infer the image type, if the content is text, it can check for a byte order mark etc. But since the data can be just about anything, it is impossible for the UA to do such an inferrence.

您已指定内容类型 application/octet-stream .这意味着您要告诉UA内容是二进制数据.UA就是这样对待它的.如果要将数据识别为图像,则需要指定正确的内容类型. application/octet-stream 是不够的.

You have specified the content type application/octet-stream. That means you are telling the UA that the content is binary data. And that's how the UA is treating it. If you want the data to be recognized as an image, you need to specify the correct content type; application/octet-stream will not be enough.

当存储可以是任何类型的数据时,绝对有必要将MIME类型与数据一起存储.如果您从光盘中读取数据,则也许可以从文件扩展名中找出内容类型,但是您的服务器需要这样做,因为UA无法这样做.

When you store data that can be of any type, it is absolutely necessary for you to store the MIME type with the data. If you read the data from disc, you might be able to inder the content type from the file extension, but your server needs to do that, because the UA can't.

这篇关于所有类型的文件都应使用哪种内容类型在asp.net中下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆