Change Download File Name in Cocoahttpserver

2019-04-14 15:04发布

I'm using cocoahttpserver in an iphone app, but when I try to download it (by clicking a link in the standard demo app), my sqlite file (myDatabase.sqlite) arrives on my Mac Desktop as "Unknown" with no suffix at all. However, when I "Save As..." it provides the name fine. I would prefer it to save the file with the sqlite suffix.

So, it must be the suffix causing the problems????

If this is the problem, I cannot seem to find a way in the classes to download the correct file name BUT then change it when presenting it to the browser (with a suffix like .backup, or .db, or something that works).

Anyone know where in the classes to change the download file name so the browser (Safari) will not call it "unknown"? Thanks.

3条回答
混吃等死
2楼-- · 2019-04-14 15:31

I found someone else's code (MyAppSales) and in replyToHTTPRequest, I added the Content-Disposition header as below (in one section of the method), and now it works!

if(!isRangeRequest)
        {
            // Status Code 200 - OK
            response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1);

            NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", contentLength];
            CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), (CFStringRef)contentLengthStr);

            // ************* added this from MyAppSales
            if ([httpResponse isKindOfClass:[HTTPFileResponse class]])
            {
                NSString *baseName = [(NSString *)[(HTTPFileResponse *)httpResponse filePath] lastPathComponent];

                NSString *contentDispoStr = [NSString stringWithFormat:@"Content-Disposition: attachment; filename=\"%@\"", baseName];
                CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Disposition"), (CFStringRef)contentDispoStr);
            }

        }
查看更多
smile是对你的礼貌
3楼-- · 2019-04-14 15:36

The proper way to do this is to use the httpHeaders override in your async file class:

- (NSDictionary *)httpHeaders
{
    NSString *key = @"Content-Disposition";
    NSString *value = [NSString stringWithFormat:@"attachment; filename=\"%@\"", [filePath lastPathComponent]];

    return [NSDictionary dictionaryWithObjectsAndKeys:value, key, nil];
}
查看更多
狗以群分
4楼-- · 2019-04-14 15:45

I had a same problem and solved it by changing client side code. At the client side I add download attribute to tags.

<a href="/get" download="FILE_NAME">Download</a> 

For Example:

<a href="/get" download="file.backup">Download</a> 
查看更多
登录 后发表回答