1

我有一个 ASP.NET MVC3 应用程序,我想链接到一个图像文件(png、jpeg、gif 等),当用户点击它时,该文件会下载,而不是浏览器显示它;有什么办法吗?

4

4 回答 4

3

获取您的链接,如下所示:

@Html.ActionLink(
    "Download Image", // text to show
    "Download", // action name
    ["DownloadManager", // if need, controller]
    new { filename = "my-image", fileext = "jpeg" } // file-name and extension 
)

和行动方法在这里:

public FilePathResult Download(string filename, string fileext) {
    var basePath = Server.MapPath("~/Contents/Images/");
    var fullPath = System.IO.Path.Combine(
        basePath, string.Concat(filename.Trim(), '.', fileext.Trim()));
    var contentType = GetContentType(fileext);
    // The file name to use in the file-download dialog box that is displayed in the browser.
    var downloadName = "one-name-for-client-file." + fileext;
    return File(fullPath, contentType, downloadName);
}

private string GetContentType(string fileext) {
    switch (fileext) {
        case "jpg":
        case "jpe":
        case "jpeg": return "image/jpeg";
        case "png": return "image/x-png";
        case "gif": return "image/gif";
        default: throw new NotSupportedException();
    }
}

更新:事实上,当文件发送到浏览器时,这个键/值将在http-header中生成:

Content-Disposition: attachment; filename=file-client-name.ext

file-client-name.ext是您希望文件在客户端系统上另存为的name.extension ;例如,如果您想在 ASP.NET(无 mvc)中执行此操作,您可以创建一个HttpHandler,将文件流写入Response,然后将上述键/值添加到http-header

Response.Headers.Add("Content-Disposition", "attachment; filename=" + "file-client-name.ext");

就这个,享受吧:D

于 2011-08-02T17:50:52.970 回答
0

从技术上讲,您的浏览器正在下载它。

我认为您不能直接链接到图像,并让浏览器提示下载。

您可以尝试一些方法,而不是直接链接到图像,而是链接到一个页面,该页面可能以 zip 文件的形式提供图像 - 这当然会促使下载发生。

于 2011-08-02T17:36:01.313 回答
0

是的你可以。

现在,您需要对其进行自定义以满足您的需要,但我创建了一个FileController通过标识符返回的文件(您可以轻松地按名称返回)。

public class FileController : Controller
{
    public ActionResult Download(string name)
    {
        // check the existence of the filename, and load it in to memory

        byte[] data = SomeFunctionToReadTheFile(name);
        FileContentResult result = new FileContentResult(data, "image/jpg"); // or whatever it is
        return result;
    }
}

现在,如何读取该文件或从何处获取它取决于您。然后我创建了一条这样的路线:

 routes.MapRoute(null, "files/{name}", new { controller = "File", action = "Download"});

我的数据库有一个标识符到文件的映射(它实际上比这更复杂,但为了简洁起见,我省略了这个逻辑),我可以编写如下 URL:

 "~/files/somefile"

并下载相关文件。

于 2011-08-02T17:45:45.773 回答
-1

我认为这是不可能的,但我认为一条简单的消息说右键单击以保存图像就足够了。

于 2011-08-02T17:40:05.987 回答