Change Download File Name in Cocoahttpserver

我们两清 提交于 2019-12-21 21:11:43

问题


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.


回答1:


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



回答2:


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

        }



回答3:


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> 


来源:https://stackoverflow.com/questions/1780368/change-download-file-name-in-cocoahttpserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!