使用HTTP响应传输文件的正确方式是什么



我正在尝试构建一个能够传输文件的简单web服务器
我知道,有很多例子,但对于从未使用过HTTP的人来说,其中大多数太复杂了,无法理解
所以我。。。

    public Hashtable MimeTypes = new Hashtable();
    public HttpServer(int port)
    {
        this.port = port;
        MimeTypes.Add("html", "text/html");
        MimeTypes.Add("htm", "text/html");
        MimeTypes.Add("css", "text/css");
        MimeTypes.Add("js", "application/x-javascript");
        MimeTypes.Add("png", "image/png");
        MimeTypes.Add("gif", "image/gif");
        MimeTypes.Add("jpg", "image/jpeg");
        MimeTypes.Add("jpeg", "image/jpeg");
    }
    public void writeSuccess(string mime_type, string file_name, int file_size)
    {
        outputStream.Write("HTTP/1.0 200 OKn");
        outputStream.Write("Content-Type: " + mime_type + "n");
        if (file_name != null)//if file name isn't null, this mean we need to add additional headers
        {
            outputStream.Write("Content-Disposition: attachment; filename=" + file_name);
            outputStream.Write("Content-Length: " + file_size);
        }
        outputStream.Write("Connection: closen");
        outputStream.Write("n");
    }
public override void handleGETRequest(HttpProcessor p)
{
    Console.WriteLine("request: {0}", p.http_url);
    byte[] file_content = null;
    try { file_content = File.ReadAllBytes(work_folder + p.http_url); } //tring to read requested file
    catch (Exception exc) { p.writeFailure(); return; } //return failure if no such file
    string[] splitted_html_url = p.http_url.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries ); //splitting url for future format check
    string mime_type = "application/octet-stream"; //the most generic type
    if (MimeTypes.Contains(splitted_html_url[splitted_html_url.Length - 1]))
        mime_type = (string)MimeTypes[splitted_html_url[splitted_html_url.Length - 1]]; //set mimy type that math to requested file format
    if (mime_type.Contains("image") || mime_type == "application/octet-stream") //hacky thing for tests...
        p.writeSuccess(mime_type, p.http_url.Remove(0, 1), file_content.Length); //if mime type is image or unknown, than pass file name and length to responce builder
    else
        p.writeSuccess(mime_type, null, 0); //er else just add general headers
    p.outputStream.Write(Encoding.ASCII.GetString(file_content)); //write file content after headers
}

它适用于HTML传输,但我无法使它传输图像:(
如果我用这个标签制作html页面:

<img src = "logo225x90.gif" width = "100%" height = "100%" />

并将该文件放在正确的目录中,它在浏览器中仍然显示为丢失的文件

我认为你犯了多个错误。

  • 您假设可以避免示例代码的所有复杂性
  • 与其粘贴你的代码并让别人做你的工作,你应该自学HTTP——这对你的任务范围来说应该不会太难
  • 您正在编写代码以执行某些可以由运行您的代码的IIS执行的操作(如果您在IIS上运行代码)
  • 您正在使用p.outputStream.Write(Encoding.ASCII.GetString(file_content)); //write file content after headers 将文件写入字符串

我建议:

  • 不要使用您正在使用的CodeProject示例
  • 尝试ServiceStack项目(您可能想要读取ServiceStack并返回流)

最新更新