15 Aug 2012

使用AjaxUpload和Carrierwave在Rails Mongoid中批量上传图片

file-uploader是一个用 Javascrit 编写的文件上传 Libary,在这里我使用CarrierWaveMongoid 来完成多文件的无刷新上传功能

RubyGems

gem 'mongoid', '3.0.4'
gem 'carrierwave', '0.6.2'
gem 'carrierwave-mongoid', :github => 'jnicklas/carrierwave-mongoid', :branch => 'mongoid-3.0' 
gem 'mini_magick', '3.4'
gem 'rack-raw-upload', '1.1.0'

Model

class Screenshot
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  include Rails.application.routes.url_helpers

  attr_accessible :image 
  field :image 

  mount_uploader :image, ScreenshotUploader 

end

Controller

class ScreenshotsController < ApplicationController

  def index
    @screenshots = Screenshot.all.desc(:created_at)

    respond_to do |format|
      format.html # index.html.erb    
      format.js{ render :layout => false}
    end
  end

  def create
    file = params[:qqfile].is_a?(ActionDispatch::Http::UploadedFile) ? params[:qqfile] : params[:file]
    @screenshot = Screenshot.new
    @screenshot.image = file
    if @screenshot.save
      render json: { success: true, src: @screenshot.to_json }
    else
      render json: @screenshot.errors.to_json
    end
  end

  def destroy
    @screenshot = Screenshot.find(params[:id])
    @screenshot.destroy

    respond_to do |format|
      format.html { redirect_to screenshots_path }
      format.js{ 
        @screenshots = Screenshot.all.desc(:created_at)
        render :layout => false
      }
    end

  end

end

Uploader

# encoding: utf-8
require "digest/md5"
require 'carrierwave/processing/mini_magick'

class ScreenshotUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :file

  # Override the directory where uploaded files will be stored.
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end


  process :convert => 'png'

  # Create different versions of your uploaded files:
  version :thumb do
    process :resize_to_fill => [120, 120]
  end

  # Add a white list of extensions which are allowed to be uploaded.
  def extension_white_list
    %w(jpg jpeg gif png)
  end

  # Override the filename of the uploaded files:
  # see http://huacnlee.com/blog/carrierwave-upload-store-file-name-config/
  def filename
    if super.present?
      # current_path 是 Carrierwave 上传过程临时创建的一个文件,有时间标记,所以它将是唯一的
      @name ||= Digest::MD5.hexdigest(File.dirname(current_path))
      "#{@name}.#{file.extension.downcase}"
    end
  end
end

Javascript

  $(document).ready(function(){

    var uploader = new qq.FileUploader({
      debug: true,
      allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
      sizeLimit: 1048576, // max size: 1MB
      minSizeLimit: 0, // min size
      multiple: true,
      element: document.getElementById('file-uploader'),
      action: '<%= screenshots_path %>',
      onComplete: function(id, fileName, responseJSON){
        $.getScript("<%= screenshots_path %>");
      },
      onSubmit: function(id, fileName) {
        uploader.setParams({
          xx: "xx",
          yy: 'yy',
          zz: 'zz',       
          authenticity_token: "<%= form_authenticity_token.to_s %>"
        });
      }
    });

});

你可以在 https://github.com/huobazi/ajax-upload-with-carrierwave-mongoid下载完整的示例代码

03 Apr 2008

MS Ajax 客户端生命周期

The flowing reference  is an excellent post !!!

http://aspnetresources.com/downloads/MS%20Ajax%20Client%20Life-Cycle%20Events.pdf


02 Nov 2007

FckEditor,远程图片下载,插件
有时候我们从其他网页上拷贝来的内容中含有图片,当原始地址失效后就会影响读者阅读。
所以我制作了这样一个插件,可以将远程图片保存到本地服务器。声明:下面的文字是本文不可缺少的部分,转载请保留,谢谢!
////////////////////////////////////////////////////
作者:武眉博<活靶子.NET>
同时首发于:
    落伍者   && 博客园  
    开发者学院   && .Net男孩社区
////////////////////////////////////////////////////
今天转载了xiaozhuang朋友的文章同时从博客园服务器上下载了图片
演示见:http://www.devedu.com/Doc/DotNet/AspNet/AspNet-AjaxWCF-ServiceADONET-Entity-FrameworkShiXianShuJuLieBiaoShuJuShaiXuanFenYePaiXuShanChu.aspx


原理如下:
    1.实现ICallbackEventHandler接口以用启用客户端回调。
    2.从当前FckEdiotr内容分析出所有<img标签,取得src的地址。
    3.回调下载到服务器。
    4.返回下载后位于本服务器上的路径。
    5.替换当前FckEdiotr内容内对应的<img标签的src属性。 
 


 


其他废话不多说了,代码中都有注释。

如果您熟悉Fckeditor的插件工作流程,请继续向下阅读,另请不要留言要我直接提供下载,下面的代码已经可以完整调试了。
E:\IISROOT\FckTest\FckTest\fckeditor\editor\plugins\remoteimagerubber\remoteimagerubber.aspx
 


 

 


 

  1 <%--
  2 使用单页模型(非代码后置),是为了便于此插件部署,
  3 不需编译成dll,只需拷贝remoteimagerubber.aspx 和 fckplugin.js 到plugn目录,
  4 并配置一下fckconfig.js及相应的语言包,就可以使用了。
  5 --%>
  6 
  7 <%@ Page Language="C#" %>
  8 
  9 <%@ Import Namespace="System.Net" %>
 10 <%--
 11 实现ICallbackEventHandler接口以提供客户端回调功能。
 12 --%>
 13 <%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>
 14 
 15 <script runat="server">
 16     
 17     /// <summary>
 18     /// 此处配置远程文件保存目录
 19     /// </summary>
 20     private static readonly string savePath = "~/Uploads/";
 21 
 22     /// <summary>
 23     /// 此处配置允许下载的文件扩展名
 24     /// <remarks>
 25     ///     暂未考虑使用动态网页输出的图片如:http://site/image.aspx?uid=00001 这样的URI;
 26     ///  若要实现此功能可读取流并判断ContentType,将流另存为相应文件格式即可。
 27     /// </remarks>
 28     /// </summary>
 29     private static readonly string[ ] allowImageExtension = new string[ ] { ".jpg" , ".png" , ".gif" };
 30 
 31     /// <summary>
 32     /// 此处配置本地(网站)主机名
 33     /// </summary>
 34     private static readonly string[ ] localhost = new string[ ] { "localhost" , "www.devedu.com" };
 35 
 36     private string localImageSrc = string.Empty;
 37 
 38     private void Page_Load( object obj , EventArgs args )
 39     {
 40         if ( !Page.IsPostBack )
 41         {
 42             ClientScriptManager csm = Page.ClientScript;
 43 
 44             string scripCallServerDownLoad = csm.GetCallbackEventReference( this , "args" , "__ReceiveServerData" , "context" );
 45             string callbackScriptDwonLoad = "function __CallServerDownLoad(args , context) {" + scripCallServerDownLoad + "; }";
 46             if ( !csm.IsClientScriptBlockRegistered( "__CallServerDownLoad" ) )
 47             {
 48                 csm.RegisterClientScriptBlock( this.GetType( ) , "__CallServerDownLoad" , callbackScriptDwonLoad , true );
 49             }
 50         }
 51     }
 52 
 53     #region ICallbackEventHandler 成员
 54 
 55     /// <summary>
 56     /// 返回数据
 57     /// </summary>
 58     /// <remarks>如果处理过程中出现错误,则仍然返回远程路径</remarks>
 59     /// <returns>服务器端处理后的本地图片路径</returns>
 60     public string GetCallbackResult( )
 61     {
 62         return localImageSrc;
 63 
 64     }
 65 
 66     /// <summary>
 67     /// 处理回调事件 
 68     /// </summary>
 69     /// <param name="eventArgument">一个字符串,表示要传递到事件处理程序的事件参数</param>
 70     public void RaiseCallbackEvent( string eventArgument )
 71     {
 72 
 73         string remoteImageSrc = eventArgument;
 74 
 75         string fileName = remoteImageSrc.Substring( remoteImageSrc.LastIndexOf( "/" ) + 1 );
 76         string ext = System.IO.Path.GetExtension( fileName );
 77 
 78         if ( !IsAllowedDownloadFile( ext ) )
 79         {
 80             //非指定类型图片不进行下载,直接返回原地址。
 81             localImageSrc = remoteImageSrc;
 82             return;
 83         }
 84 
 85         Uri uri = new Uri( remoteImageSrc );
 86         if ( IsLocalSource( uri ) )
 87         {
 88             //本地(本网站下)图片不进行下载,直接返回原地址。
 89             localImageSrc = remoteImageSrc;
 90             return;
 91         }
 92 
 93         try
 94         {
 95             //自动创建一个目录。
 96             DateTime now = DateTime.Now;
 97             string datePath = string.Format( @"{0}\{1}\{2}\{3}" , now.Year , now.Month.ToString( "00" ) , now.Day.ToString( "00" ) , Guid.NewGuid( ).ToString( ) );
 98 
 99             string localDirectory = System.IO.Path.Combine( Server.MapPath( savePath ) , datePath );
100             if ( !System.IO.Directory.Exists( localDirectory ) )
101             {
102                 System.IO.Directory.CreateDirectory( localDirectory );
103             }
104 
105             string localFilePath = System.IO.Path.Combine( localDirectory , fileName );
106 
107             //不存在同名文件则开始下载,若已经存在则不下载该文件,直接返回已有文件路径。
108             if ( !System.IO.File.Exists( localFilePath ) )
109             {
110                 Client.DownloadFile( uri , localFilePath );
111             }
112 
113             string localImageSrc = ResolveUrl( "~/" + localFilePath.Replace( Server.MapPath( "~/" ) , string.Empty ).Replace( "\\" , "/" ) );
114 
115         }
116         catch
117         {
118             //下载过程中出现任何异常都不抛出(  有点狠啊 :)  ),仍然用远程图片链接。
119             localImageSrc = remoteImageSrc;
120         }
121 
122     }
123 
124 
125     #endregion
126 
127     private WebClient client;
128 
129     /// <summary>
130     /// <see cref="System.Net.WebClient"/>
131     /// </summary>
132     public WebClient Client
133     {
134         get
135         {
136             if ( client != null )
137             {
138                 return client;
139             }
140 
141             client = new WebClient( );
142             client.Headers.Add( "user-agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;)" );
143 
144             return client;
145 
146         }
147     }
148 
149     /// <summary>
150     /// 判断Uri是否为本地路径
151     /// </summary>
152     /// <param name="uri"></param>
153     /// <returns></returns>
154     private bool IsLocalSource( Uri uri )
155     {
156         for ( int i = localhost.Length ; -->= 0 ; )
157         {
158             if ( localhost[ i ].ToLower( ) == uri.Host.ToLower( ) )
159             {
160                 return true;
161             }
162         }
163 
164         return false;
165 
166     }
167 
168     /// <summary>
169     /// 检测文件类型是否为允许下载的文件类型
170     /// </summary>
171     /// <param name="extension">扩展名 eg: ".jpg"</param>
172     /// <returns></returns>
173     private bool IsAllowedDownloadFile( string extension )
174     {
175         for ( int i = allowImageExtension.Length ; -->= 0 ; )
176         {
177             if ( allowImageExtension[ i ].ToLower( ) == extension.ToLower( ) )
178             {
179                 return true;
180             }
181         }
182 
183         return false;
184     }
185     
186 </script>
187 
188 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
189 <html xmlns="http://www.w3.org/1999/xhtml">
190 <head runat="server">
191     <title></title>
192     <style type="text/css">
193     body { margin: 0px; overflow: hidden;  background-co

04 Mar 2007

Ajax Control Toolkit 出新版了





Ajax Control Toolkit 出新版了
http://www.codeplex.com/AtlasControlToolkit/Release/ProjectReleases.aspx



Release 10301 Production
三月-01-20072 Files
Description
2007-03-01 release of the AJAX Control Toolkit includes two new controls (ListSearch and SlideShow), a number of fixes identified as important by the community, and three significant enhancements: localization support, automatic JavaScript comment stripping, and ASP.NET theme/skin support. It continues to target the new ASP.NET AJAX v1.0 release (http://ajax.asp.net/).

AjaxControlToolkit.zip is the full release package with complete source code to all controls, the test framework, VSI, and more.

AjaxControlToolkit-NoSource.zip contains only the sample web site and VSI and is for people who don’t need or want the source code for the controls.





Runtime Binaries
AjaxControlToolkit-NoSource.zip - 1542 Downloads (2.3 MB)
AjaxControlToolkit.zip - 4334 Downloads (3.3 MB)