jQuery AjaxUpload 업로드 이미지 code_jquery

WBOY
풀어 주다: 2016-05-16 15:16:19
원래의
1248명이 탐색했습니다.

이번에는 AJAXUPLOAD가 업로드 클라이언트 브러시리스 업로드 플러그인으로 사용됩니다. 공식 주소는 http://valums.com/ajax-upload/
입니다.

jquery.min.1.4.2.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("
", ""); if (k == '-1') { alert('您上传的文件太大啦!请不要超过150K'); } else { alert("服务器端传回的串:"+k); alert("本地文件名称:"+file); $("#txtFileName").val(k); $("").appendTo($('#imglist')).attr("src", k); } } }); });
로그인 후 복사

서버측 ajaxuploadhandler.ashx 코드

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;
}
로그인 후 복사

PHP 웹사이트 개발에서 파일 업로드 기능을 자주 사용하게 되는데, 이전에 PHP를 사용하여 파일 업로드 기능을 구현하는 방법을 소개한 적이 있습니다. WEB 기술의 발전으로 사용자 경험은 웹 사이트의 성공을 측정하는 열쇠가 되었습니다. 오늘 저는 Jquery를 사용하여 PHP에서 Ajax 파일 업로드 기능을 구현하는 방법에 대한 예를 여러분과 공유하겠습니다. 단일 파일 및 다중 파일 업로드 기능을 구현할 수 있는 것을 사용합니다.

Ajax업로드

Jquery 플러그인 AjaxUpload가 파일 업로드 기능을 구현하면 양식 양식을 작성할 필요가 없습니다. Ajax 모드에서 파일 업로드를 실현할 수 있습니다. 물론 필요에 따라 양식 양식을 작성할 수도 있습니다.

준비

1. Jquery 개발 패키지와 파일 업로드 플러그인 AjaxUpload를 다운로드합니다.

2. uploadfile.html을 생성하고 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가 upload_button 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 매개변수는 업로드된 파일의 유형과 수를 나타냅니다. 기본값은 이미지를 업로드하려는 경우 모든 유형의 파일만 업로드할 수 있다는 것입니다. 파일 또는 여러 파일을 동시에 저장할 수 있습니다. 이 두 변수의 값은 pic 등이 됩니다.

6~8행: 서버에 대한 POST 데이터 정적 값을 설정하거나 양식의 INPUT 값 등 Jquery의 DOM 작업 함수를 통해 일부 동적 값을 얻을 수 있습니다.

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.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!