Jquery AjaxUploadを使って画像をアップロードします。

17483 ワード

ソース:http://www.cnblogs.com/hxling/archive/2010/07/05/1771320.html
今回はAJAXUPLOADを使って、クライアントをアップロードするための無ブラシアップロードプラグインとして、その最新バージョンは3.9で、公式アドレスはhttp://valums.com/ajax-upload/です。
ページにjquery.min.1.0.22.jsとajaxupload.jsを紹介します。
<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="Scripts/ajaxupload3.9.js" type="text/javascript"></script>
HTMLコード:
<style type="text/css">
        #txtFileName {
            width: 300px;
        }
        .btnsubmit{border-bottom: #cc4f00 1px solid; border-left: #ff9000 1px solid;border-top: #ff9000 1px solid;   border-right: #cc4f00 1px solid;text-align: center; padding: 2px 10px; line-height: 16px; background: #e36b0f;  height: 24px; color: #fff; font-size: 12px; cursor: pointer;}
    </style>

    :<input type="text" id="txtFileName" /><div  id="btnUp" style="width:300px;" class=btnsubmit >  </div>
<div id="imglist"></div>
 jsコード:
<script type="text/javascript">

    $(function () {
        var button = $('#btnUp'), interval;
        new AjaxUpload(button, {
            //action: 'upload-test.php',             
            action: '/handler/AjaxuploadHandler.ashx',
            name: 'myfile',
            onSubmit: function (file, ext) {
                if (!(ext && /^(jpg|jpeg|JPG|JPEG)$/.test(ext))) {
                    alert('       ,    jpg      !', '    ');
                    return false;
                }

                // change button text, when user selects file
                button.text('   ');

                // If you want to allow uploading only 1 file at time,
                // you can disable upload button
                this.disable();

                // Uploding -> Uploading. -> Uploading...
                interval = window.setInterval(function () {
                    var text = button.text();
                    if (text.length < 10) {
                        button.text(text + '|');
                    } else {
                        button.text('   ');
                    }
                }, 200);
            },
            onComplete: function (file, response) {
                //file       ,response          
                button.text('    (     JPG     ,      150K)');
                
                window.clearInterval(interval);

                // enable upload button
                this.enable();

                var k = response.replace("<PRE>", "").replace("</PRE>", "");

                if (k == '-1') {
                    alert('         !     150K');
                }
                else {
                    alert("        :"+k);
                    alert("      :"+file);
                    $("#txtFileName").val(k);
                    $("<img />").appendTo($('#imglist')).attr("src", k);
                }
            }
        });

    });
</script>
サーバー端ajaxuploadhander.asxコード
public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            HttpPostedFile postedFile = context.Request.Files[0];
            string savePath = "/upload/images/";
            int filelength = postedFile.ContentLength;
            int fileSize = 163600; //150K
            string fileName = "-1"; //          
            if (filelength <= fileSize)
            {

                byte[] buffer = new byte[filelength];

                postedFile.InputStream.Read(buffer, 0, filelength);

                fileName = UploadImage(buffer, savePath, "jpg");

            }

            context.Response.Write(fileName);
        }

        public static string UploadImage(byte[] imgBuffer, string uploadpath, string ext)
        {
            try
            {
                System.IO.MemoryStream m = new MemoryStream(imgBuffer);

                if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadpath)))
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadpath));

                string imgname = CreateIDCode() + "." + ext;

                string _path = HttpContext.Current.Server.MapPath(uploadpath) + imgname;

                Image img = Image.FromStream(m);
                if (ext == "jpg")
                    img.Save(_path, System.Drawing.Imaging.ImageFormat.Jpeg);
                else
                    img.Save(_path, System.Drawing.Imaging.ImageFormat.Gif);
                m.Close();

                return uploadpath + imgname;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        public static string CreateIDCode()
        {
            DateTime Time1 = DateTime.Now.ToUniversalTime();
            DateTime Time2 = Convert.ToDateTime("1970-01-01");
            TimeSpan span = Time1 - Time2;   //span              
            string t = span.TotalMilliseconds.ToString("0");

            return t;
        }
..。
..。
..。
ソース:http://www.leapsoul.cn/?p=304
PHPサイトの開発では、ファイルアップロード機能はよく使われています。以前にもどのようにPHPを利用してファイルアップロード機能を実現しますか?を紹介しました。WEB技術の発展に伴って、ユーザー体験はウェブサイトの成功を測る鍵となります。今日はPHPでJqueryを利用してAjax方式のファイルアップロード機能を実現する例を共有します。その中でJqueryプラグインAjaxuploadを使用して、単一ファイルと複数ファイルアップロード機能を実現できます。 
AjaxUpload
JqueryプラグインAjaxUploadはファイルのアップロード機能を実現する時formフォームを作成する必要がなくて、Ajax方式のファイルのアップロードを実現できます。もちろん必要に応じてフォームを作成することもできます。
準備工作
1、ダウンロードJquery開発パッケージとファイルアップロードプラグインAjaxUpload
2、uploadfileを作成し、Jquery開発パッケージとAjaxUploadプラグインを導入する。
<script src="js/jquery-1.3.js"></script>
<script src="js/ajaxupload.3.5.js"></script>
3、JqueryプラグインAjaxUploadの必要に応じて、Ajaxファイルのアップロード機能をトリガするDIVを作成します。
<ul> 
    <li id="example"> 
    <div id="upload_button">    </div>
    <p>        :</p> 
            <ol class="files"></ol>
</ul>
注:下記のコードからJqueryプラグインAjaxUploadを見ることができます。このDIVはファイルアップロード機能をトリガします。 
フロントJSコード
コードの中にスイッチを設置しました。必要に応じてアップロードファイルの種類に合わせて、Ajax方式で単一のファイルアップロードを実現するか、それとも複数のファイルアップロードを実現するかを設定してもいいです。
$(document).ready(function(){
    var button = $('#upload_button'), interval;
    var fileType = "all",fileNum = "one"; 
    new AjaxUpload(button,{
        action: 'do/uploadfile.php',
        /*data:{
            'buttoninfo':button.text()
        },*/
        name: 'userfile',
        onSubmit : function(file, ext){
            if(fileType == "pic")
            {
                if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
                    this.setData({
                        'info': '       '
                    });
                } else {
                    $('<li></li>').appendTo('#example .files').text('       ,   ');
                    return false;               
                }
            }
                        
            button.text('     ');
            
            if(fileNum == 'one')
                this.disable();
            
            interval = window.setInterval(function(){
                var text = button.text();
                if (text.length < 14){
                    button.text(text + '.');                    
                } else {
                    button.text('     ');             
                }
            }, 200);
        },
        onComplete: function(file, response){
            if(response != "success")
                alert(response);
                
            button.text('    ');
                        
            window.clearInterval(interval);
                        
            this.enable();
            
            if(response == "success");
                $('<li></li>').appendTo('#example .files').text(file);                  
        }
    });
 
});
注:1行目:$(document).ready()関数、Jqueryの関数は、window.loadに似ています。この関数を使って、DOMロード準備ができたら、すぐにバインディングの関数を呼び出すことができます。
3行目:fileTypeとfileNumパラメータはアップロードファイルのタイプと数を表し、デフォルト値はすべてのタイプのファイルをアップロードすることができます。同じ時間に1つのファイルしかアップロードできません。例えば、画像ファイルをアップロードしたい場合、または複数のファイルを同時にアップロードしたい場合、これらの2つの変数値をpicとmoreに変えることができます。
6行目~8行目:POSTからサーバーまでのデータは、静的な値を設定しても良いし、JqueryのDOM操作関数によって、フォーム内のINPUTの値などダイナミックな値を得ることができます。
9行目:先端と同じ
<input type="file" name="userfile">
サーバ端$_FILES['userfile']
10~36行目:ファイルアップロード前にトリガする機能です。
11~21行目:画像ファイルタイプのフィルタ機能で、Jquery setData関数はPOSTからサーバー端までの値を設定します。
25~26行目:1つのファイルだけをアップロードするか、複数のファイルだけをアップロードするかを設定します。1つのファイルだけをアップロードすると、トリガーボタンが無効になります。いくつかのファイルを転送する場合は、サーバー側のPHPファイルアップロードプログラムにMAXSIZEの値を設定してください。もちろんアップロードファイルのサイズ制限とPHP.INIファイルの設定にも関連します。
28~35行目:ファイルアップロード中にボタンのテキストを200ミリ秒ごとに動的に更新し、動的なメッセージの効果を実現しました。window.setInterval関数は指定された時間ごとに内蔵された関数を実行するために使用されます。インタラクティブ時間の単位は豪秒です。
37~49行目:ファイルアップロード機能が完了したらトリガする機能は、返却値によってサーバー側にエラーが発生した場合、エラーメッセージをALERTで提示する。
サーバ端のPHPファイルのアップロードコード
基本的には、前に紹介したPHPファイルアップロード機能コード例教程の改編により、ファイルアップロードサイズの設定、エラー情報などの説明がここで詳しく説明されています。
$upload_dir = '../file/';
$file_path = $upload_dir . $_FILES['userfile']['name'];
$MAX_SIZE = 20000000;

echo $_POST['buttoninfo'];
if(!is_dir($upload_dir))
{
    if(!mkdir($upload_dir))
        echo "                     ";
    if(!chmod($upload_dir,0755))
        echo "                  ";
}

if($_FILES['userfile']['size']>$MAX_SIZE)
    echo "              ";

if($_FILES['userfile']['size'] == 0)
    echo "        ";

if(!move_uploaded_file( $_FILES['userfile']['tmp_name'], $file_path))
    echo "      ,     "; 

switch($_FILES['userfile']['error'])
{
    case 0:
        echo "success" ;
        break;
    case 1:
        echo "         php.ini   upload_max_filesize       ";
        break;
    case 2:
        echo "           HTML     MAX_FILE_SIZE       ";
        break;
    case 3:
        echo "         ";
        break;
    case 4:
        echo "       ";
        break;
}
締め括りをつける
基本的にフロントエンドのAjaxファイルのアップロードトリガ機能とサーバー端のPHPファイルのアップロード機能のプロトタイプは紹介済みです。ご自身の必要に応じて前後のエンドコードを補足してもいいです。また、ファイルタイプ、単一ファイルまたは複数ファイルのアップロード機能などの機能を独立して出してもいいです。全体としては、JqueryプラグインAjaxUploadは、ファイルアップロード機能のアプリケーションを実現するのが簡単です。
注:PHPサイト開発教程-leappsoul.cn著作権はすべて、転載する時はリンク形式で原始出所と本声明を明記してください。ありがとうございます。
..。
..。
..。
ソース:http://hi.baidu.com/spurringworld/blog/item/adb09b341d670ad0a2cc2bf6.html
jsファイルを紹介します。ajaxupload.jsはjava jarファイルを導入します。commons-fileuplload-12.jar。common-i-o-1.4.jarアップロードjsコード
//upload resume
new AjaxUpload('resume', {
	// Location of the server-side upload script
	// NOTE: You are not allowed to upload files to another domain
	action: '../resources/Reg1C/upload',
	// File upload name
	name: 'resume',
	// Fired after the file is selected
	// Useful when autoSubmit is disabled
	// You can return false to cancel upload
	// @param file basename of uploaded file
	// @param extension of that file
	onChange: function (file, extension) { },
	// Fired before the file is uploaded
	// You can return false to cancel upload
	// @param file basename of uploaded file
	// @param extension of that file
	onSubmit: function (file, extension)
	{
		if (!(extension && /^(doc|docx|pdf)$/i.test(extension)))
		{
			// extension is not allowed
			alert('Error: invalid file extension');
			// cancel upload
			return false;
		}
		// allow only 1 upload
		//this.disable();
	},
	// Fired when file upload is completed
	// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
	// @param file basename of uploaded file
	// @param response server response
	onComplete: function (file, response)
	{
		if ($(response).find("isSuccess").text() == "false")
		{
			alert($(response).find("msg").text());
			if ($(response).find("id").text() == "-1")
			{
				window.location.href = "../Home/index.jsp";
			}
			return;
		}
		else
		{
			$("#uploadMsg").html(file + " is uploaded!");
		}
	}
});
Java code:(RESTful)
@POST
@Path("upload")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public ResponseVO upload() throws IOException {
ResponseVO responseVO = new ResponseVO();
Integer userId = SessionStoreManager.getUserId(request);
if (userId == null) {
responseVO.setId(ResponseVO.HOME_ALERT);
responseVO.setMsg("Your session is time out!");
return responseVO;
}
try {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<FileItem> items = upload.parseRequest(request);

// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
// Process a file upload
if (!item.isFormField()) {
String fileName = item.getName();
//comment out for .docx type will get a too long string
String contentType = item.getContentType();
if (!(Resume.PDF_CONTENT_TYPE.equals(contentType)
|| Resume.DOC_CONTENT_TYPE.equals(contentType)
|| Resume.DOCX_CONTENT_TYPE.equals(contentType))) {
responseVO.setIsSuccess(false);
responseVO.setMsg("MS Word or PDF files only.");
return responseVO;
}
long sizeInBytes = item.getSize();
if (sizeInBytes > Constants.MAX_RESUME_SIZE) {
responseVO.setIsSuccess(false);
responseVO.setMsg("Error uploading the resume file. Resume file size must be less than 1M.");
return responseVO;
}
byte[] data = item.get();
//Expert entityExpert = em.find(Expert.class, userId);
Resume entityResume = em.find(Resume.class, userId);
if (entityResume == null) {
entityResume = new Resume();
entityResume.setId(userId);
em.persist(entityResume);
}
entityResume.setContent(data);
entityResume.setContentType(contentType);

responseVO.setIsSuccess(true);
responseVO.setMsg("Upload sucess!" + item.getContentType());
}
}
} catch (Exception e) {
responseVO.setIsSuccess(false);
responseVO.setMsg("Upload failed!");
}

return responseVO;
}