内容处理文件名"建议"总是被忽略。为什么?

时间:2016-04-03 15:24:31

标签: c cgi content-disposition

这是用C语言编写的CGI程序的一部分。当客户端点击链接时,我希望文件开始下载,并使用建议的默认文件名。

我知道规范明确指出Content-disposition标头中指定的文件名仅仅是SUGGESTED,但似乎无论我使用什么浏览器,它总是被忽略。我认为这种行为意味着我做错了什么。

这是一个精简的代码段,可以重现我的问题。当编译到例如test.cgi时,程序可以正常工作,但是浏览器使用文件名" test.cgi"来保存数据。而不是" archive.tar.gz"如建议的那样。

(文件i / o错误检查和其他安全位被删除,以保持清晰和简洁。)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

#define CHUNK_SIZE 1024

int main( int argc, char *argv[] ) {
  int fd;
  long bytes_remaining, bytes_to_get, bytes_read, bytes_sent, retval;
  int chunksize;
  unsigned char data_buffer[CHUNK_SIZE];
  char header_str[200];

  fd = open( "archive.tar.gz", O_RDONLY );
  if( fd == -1 ) {
    printf( "Content-type: text/html\n\n" );
    printf( "Unable to open file: %s.<br><br>\n", strerror(errno) );
    return 0;
  }

  bytes_remaining = lseek( fd, 0, SEEK_END );
  lseek( fd, 0, SEEK_SET );

  snprintf( header_str, 200, "Content-Type: application/x-compressed\r\n\r\nContent-Disposition: attachment; filename=\"archive.tar.gz\"\r\n\r\n" );
  write( 1, header_str, strlen(header_str) );

  while( bytes_remaining > 0 ) {
    if( bytes_remaining > CHUNK_SIZE ) bytes_to_get = CHUNK_SIZE;
    else bytes_to_get = bytes_remaining;
    bytes_read = read( fd, data_buffer, bytes_to_get );
    bytes_sent = write( 1, data_buffer, bytes_read );
    bytes_remaining -= bytes_sent;
  }
  close( fd );

  return 0;
}

为什么我的建议文件名一直被忽略?

谢谢。

1 个答案:

答案 0 :(得分:0)

问题是标题中有一个额外的回车/换行符。它应该是:

snprintf( header_str, 200, "Content-Type: application/x-compressed\r\nContent-Disposition: attachment; filename=archive.tar.gz\r\n\r\n" );

如在OP中所写,Content-Disposition行将被解释为数据的一部分,而不是标题的一部分。此外,不需要引用建议的文件名。

相关问题