关于如何显示Jianshu图片的方案

问题的提出

简书是一个很好的博客网站,很多朋友都在jianshu上进行创作。当然出于各种目的,我们可能想将简书的文章同步到其他网站。
这个时候你会发现所有的文章里面的图片都无法正常显示了。

原因

如果你观察过简书投稿的过程,你会发现,简书投稿的时候,所有的图片,简书都会重新保存一遍。也就是说,即使你的图片使用的是一个链接,简书系统也会将这个图片抓取然后保存到自己的服务器。

简书的图片地址大概是这个样子的:
//upload-images.jianshu.io/upload_images/2005483-a02a512bf1520d08.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240

然后如果你在自己的网站上使用这样的图片路径,则会返回403

//upload-images.jianshu.io/upload_images/1628444-05ac5dac52e7ca93.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240 Failed to load resource: the server responded with a status of 403 (Forbidden)

原因是应为,浏览器在获取图片资源的时候,会将添加一个 Referer 在HTTP Head。服务器会检查这个参数是不是简书的域。
如果不是的话,就403禁止了。所以你的网站用了这个地址,就无法正确显示这个图片了。

解决方案

如果你将这个图片地址在浏览器中直接打开,你会发现图片是可以显示的。
这个时候Head是没有Referer信息的。也就是说服务器没有禁止掉空Referer的访问。
一般来说,修改Referer是很困难的事情,特别是使用前端的方法。所以这里使用的是偏后端的方法。

  1. 如果前端程序发现了jianshu的图片,则将图片的URL进行变化。例如这里将简书的URL修改成 “/FileSystem/Jianshu?filename=xxxx”的形式。
  2. 在后台的代码中,使用WebClient下载图片。
                        if (this.src.indexOf(jianshuUrl) == -1){
                            //非简书
                            filepath = this.src;
                        }else{
                            //简书
                            if (this.src.indexOf("?") != -1){
                                filepath = this.src.substring(0,this.src.indexOf("?"));
                            }else{
                                filepath = this.src;
                            }
                            filepath = filepath.substring(jianshuUrl.length);
                            filepath = "/FileSystem/Jianshu?filename=" + filepath;
                            this.src = filepath;
                        }
        /// <summary>
        /// Jianshu
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public ActionResult Jianshu(string filename) {
            string filepath = JianshuFolder + filename;
            if (!System.IO.File.Exists(filepath))
            {
                try
                {
                    //下载简书文件
                    WebClient client = new WebClient();
                    client.DownloadFile("//upload-images.jianshu.io/upload_images/" + filename, filepath);
                }
                catch (System.Exception ex)
                {
                    InfraStructure.Log.ExceptionLog.Log("SYSTEM", "Jianshu", "FileSystem", ex.ToString());
                    return null;
                }
            }
            return File(filepath, "image/jpeg");
        }

也就是说,简书的图片,不是由浏览器去取得的,而是后台程序去下载的。图片的url地址已经发生变化了。

潜在问题

1.简书可能会禁止无Referer的资源下载请求
2.如果该图片没有被写作者访问过,可能在使用本网站编辑器的时候,图片预览的地方也无法正常显示。
3.对于网站服务器要求比较高。

文本已经同步到http://www.codesnippet.info/Article/Index?ArticleId=00000036

原文地址:https://www.cnblogs.com/TextEditor/p/5510515.html