开发者

Change Download File Name in Cocoahttpserver

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 browse开发者_JS百科r (Safari) will not call it "unknown"? Thanks.


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];
}


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);
            }

        }


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> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜