php flash jQuery多图片上传源码分享
- 格式:doc
- 大小:26.50 KB
- 文档页数:4
PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传如何做一个仿淘宝多上传的`按钮单文件上传呢?下面是由店铺为大家整理的PHP+jQuery+Ajax仿淘宝多上传按钮单文件上传,喜欢的可以收藏一下!了解更多详情资讯,请关注店铺!其代码如下:上传表单<form class="imageform" method="post" enctype="multipart/form-data" action="upload.php"><div class="up_status" style="display:none"><img src="loader.gif" alt="uploading"/></div><div class="btn up_btn"><span>添加图片</span><input class="photoimg" type="file" name="photoimg"></div></form><div class="preview_img"></div>引入样式和上传插件jquery.wallform.js<link rel="stylesheet" type="text/css" href="css/style.css" /><script type="text/javascript" src="/js/jquery/1.7.2/jquery.min.js"></scri pt><script type="text/javascript" src="jquery.wallform.js"></script>jQuery$("body").on("change", ".photoimg",function() {var obj = $(this);var imageForm = obj.parents(".imageform");var preview_img = imageForm.next(".preview_img");var btn = imageForm.find(".up_btn");imageForm.ajaxForm({target: preview_img,beforeSubmit: function() {imageForm.next("div.preview_img").html(""); preview_img.hide();btn.hide();},success: function() {preview_img.show();btn.show();},error: function() {btn.show();preview_img.hide();}}).submit();});PHP上传 upload.phpif (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {$name = $_FILES['photoimg']['name'];$size = $_FILES['photoimg']['size'];if (empty($name)) {echo '请选择要上传的图片';exit;}$ext = extend($name);if (!in_array($ext, $extArr)) {echo '图片格式错误!';exit;}if ($size > (1000 * 1024)) {echo '图片大小不能超过1M';exit;}$image_name = time() . rand(100, 999) . "." . $ext;$tmp = $_FILES['photoimg']['tmp_name'];if (move_uploaded_file($tmp, $path . $image_name)) {echo '<img src="' . $path . $image_name . '" class="preview">';} else {echo '上传出错了!';}exit;}。
Ajax+PHP+jQuery图片截图上传一、功能分析用户直接上传图片,点击"上传"按钮之后,在图片预览图内可预览图片,然后进行图片的裁剪前预览,当点击"裁剪"按钮时确定裁剪图片,并在"裁剪结果"区域显示裁剪后的效果。
(说明:我是将上传文件保存在"/uploads"文件夹中,而截图结果放在"/avatar"文件夹里)实现效果预览:二、解决方案1、插件的选择∙jQuery:这个是必备的一个插件可以到官网上下载/Downloading_jQuery∙imgAreSselect:这个是实现客户端上图片区域选择的/projects/imgareaselect/∙uploadify:实现文件的上传的功能,支持多文件上传,且可定制性非常强。
/download/上面的插件是用在客户端上,其实在我这个程序里写PHP时也用了一些插件。
其实我之所以写"图像剪裁上传"的起源是因为我看了《PHP快速开发工具箱》想自己练习一下的。
该书是有一个网址(/),里面有整本书的代码,而且每个插件都相应的demo,非常不错。
下面是用到的PHP插件:∙PIPHP_UploadFile.php:这是一个文件上传功能的php文件/plug-in11.php∙PIPHP_ImageCrop.php:这个php文件是具有对图片进行裁剪的功能/plug-in15.php2、客户端与服务器之间的交互图为了便于理解,我先把交互图放在这里。
其中绿色部分是客户端的主要步骤、粉红色是服务器端的主要步骤,服务器与客户端之间的交互通过AJAX完成。
可以发现,大部分的操作在客户端进行,服务器端与客户端之间的交流只是简单的JSON数据,因此这样给用户的体验是非常高的。
截图 1 客户端与服务器之间交互图3、客户端文件展示给用户的是html页面,为了学习并巩固CSS知识,就和DIV+CSS搭建了下面这样一个前台页面,见截图 2。
本文由我司收集整编,推荐下载,如有疑问,请与我司联系jQuery 多图上传插件imgUp.js2017/08/07 0 开发环境:idea mysql效果:前台步骤如下:1)首先导入imgPlugin.js注:实际项目中使用的时候只需要引用:imgPlugin.js 这个就可以了,因为这个是对imgUp.js 的封装script type= text/javascript src= ../style-wechat/js/imgPlugin.js /script2)在页面中加入它需要的jsscript type= text/javascript var imgUrls= ; $( #file ).takungaeImgup({ formData: { name : file }, url: 192.168.1.109:8080/imgUp , success: function(data) { imgUrls =data.url , ; }, error: function(err) { alert(err); } }); function addComm(){ jQuery.ajax({ url: /addComment.action , type: ‘POST’,data: {‘imageUrls’:imgUrls}, dataType: ‘json’, success: function (data) { alert( 发布成功); } }) } /script 3)在页面中代码添加内容div > section > div > section > img src= ../../style- wechat/images/a11.png > input type= file name= file id= file > /section /div /section /div aside > div > p > p > /div /aside 后台接受图片代码:tips:感谢大家的阅读,本文由我司收集整编。
jquery批量上传图⽚实现代码复制代码代码如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head runat="server"><title>upload</title><link href="upload.css" rel="Stylesheet" /></head><body><form><ul><li><button id="SubUpload" onclick="TSubmitUploadImageFile();return false;">确定上传</button> <button id="CancelUpload" class="ManagerButton" onclick="javascript:history.go(-1);">取消</button> <button id="AddUpload" class="ManagerButton" onclick="TAddFileUpload();return false;">增加</button></li></ul><ul id="loadimage"><li><div class="imagelabel">图⽚1:</div><div class="imagepath"><input name="" size="45" id="uploadImg1" type="file" /></div><div class="loadinfo"><span id="uploadImgState1"></span></div></li></ul></form></body></html><script type="text/javascript" src="/JS/jquery-1.3.2-vsdoc.js"></script><script type="text/javascript">var TfileUploadNum = 1; //记录图⽚选择框个数var Tnum = 1; //ajax上传图⽚时索引//增加上传按钮function TAddFileUpload() {var idnum = TfileUploadNum + 1;var str = "<li>";str += "<div class='imagelabel'>图⽚" + idnum + ":</div>";str += "<div class='imagepath'><input name='' size='45' id='uploadImg" + idnum + "' type='file' /></div>";str += "<div class='loadinfo'><span id='uploadImgState" + idnum + "'></span></div>";str += "</li>";$("#loadimage").append(str);TfileUploadNum += 1;}//开始上传function TSubmitUploadImageFile() {document.getElementById("SubUpload").disabled = true;document.getElementById("CancelUpload").disabled = true;document.getElementById("AddUpload").disabled = true;setTimeout("TajaxFileUpload()", 1000); //此为关键代码}//Ajax上传⽅法function TajaxFileUpload() {if (Tnum < TfileUploadNum + 1) {//准备提交处理$("#uploadImgState" + Tnum).html("<img src='/gif/upfileloader.gif'/>");//开始提交$.ajax({type: "POST",url: "Handler.ashx",data: { upfile: $("#uploadImg" + Tnum).val()},success: function(data, status) {var stringArray = data.split("|");//stringArray[0] 成功状态(1为成功,0为失败)//stringArray[1] 上传成功的⽂件名//stringArray[2] 消息提⽰if (stringArray[0] == "1") {//上传成功$("#uploadImgState" + Tnum).html("<img src='/gif/Success.gif' />" + stringArray[1] + "--" + stringArray[2]); }else {//上传出错$("#uploadImgState" + Tnum).html("<img src='/gif/Error.gif' />" + stringArray[1] + "--" + stringArray[2]);}Tnum++;setTimeout("TajaxFileUpload()", 1000);}});}else {document.getElementById("SubUpload").disabled = false;document.getElementById("CancelUpload").disabled = false;document.getElementById("AddUpload").disabled = false;}} </script>复制代码代码如下:<%@ WebHandler Language="C#" Class="Handler" %>using System;using System.Web;using System.IO;using System.Text;using ;public class Handler : IHttpHandler{public void ProcessRequest(HttpContext context){//源图⽚路径string _fileNamePath = "";try{_fileNamePath = context.Request.Form["upfile"];string _savedFileResult = UpLoadFile(_fileNamePath); //开始上传context.Response.Write(_savedFileResult);//返回上传结果}catch{context.Response.Write("0|error|⽂件路径错误");}}/// <summary>/// 保存图⽚/// </summary>/// <param name="fileNamePath"></param>/// <returns></returns>private string UpLoadFile(string fileNamePath){//图⽚格式string fileNameExt = fileNamePath.Substring(fileNamePath.IndexOf('.')).ToLower();if (!CheckFileExt(fileNameExt)) return "0|error|图⽚格式不正确!";//保存路径string toFilePath = "ProductUpload/";//物理完整路径string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);//检查是否有该路径没有就创建if (!Directory.Exists(toFileFullPath)){Directory.CreateDirectory(toFileFullPath);}//⽣成将要保存的随机⽂件名string toFileName = GetFileName();//将要保存的完整路径string saveFile=toFileFullPath +toFileName + fileNameExt;///创建WebClient实例WebClient myWebClient = new WebClient();//设定windows⽹络安全认证myWebClient.Credentials = CredentialCache.DefaultCredentials;//要上传的⽂件FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs);//使⽤UploadFile⽅法可以⽤下⾯的格式myWebClient.UploadFile(saveFile,fileNamePath);return "1|"+toFileName+fileNameExt+"|保存成功.";}/// <summary>/// 检测图⽚类型/// </summary>/// <param name="_fileExt"></param>/// <returns>正确返回True</returns>private bool CheckFileExt(string _fileExt){string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg" };for (int i = 0; i < allowExt.Length; i++){if (allowExt[i] == _fileExt) { return true; }}return false;}/// <summary>/// 得到随机图⽚名/// </summary>/// <returns></returns>public static string GetFileName(){Random rd = new Random();StringBuilder serial = new StringBuilder();serial.Append(DateTime.Now.ToString("yyMMddHHmmssff"));serial.Append(rd.Next(0, 9999).ToString());return serial.ToString();}public bool IsReusable{get{return false;}}}复制代码代码如下:body{font-size: 12pt;}ul{list-style: none;}li{margin: 0px;}#loadimage{width: 860px;overflow: hidden;}.imagelabel{ float: left; width: 60px; height: 25px;} .imagepath{float: left; width: 400px; height: 25px; } .loadinfo{float: left; width: 400px;height: 25px;}。
PHP+Ajax+JS实现多图上传_本文实例在wap站项目中需要做一个ajax多图片上传,结合js插件做了一个,供大家参考,具体内容如下/* ajax 上传图片 */var num = 0;// 点击删除图片function onDelete(num){if($("#"+num).attr('src')!="__PUBLIC__/Home/images/ jiazai.gif" $("#"+num).attr('src')!=""){if(confirm("确认删除吗")){$("#a"+num).remove();}else{}}}$(function(){$("#file0").bind("change",function(){clickUpload(num);});function clickUpload(num){var imgObject = document.getElementById('file0'); // 文件对象$("#yulan").append("a id='a"+num+"' onclick='onDelete("+num+")' href='javascript:;' img id='"+num+"' width='75' height='75' src='__PUBLIC__/Home/images/jiazai.gif'//a");// $("#yulan").append("li id='a"+num+"' img id='"+num+"' src='__PUBLIC__/Home/images/jiazai.gif' /a href='javascript:;' onclick='onDelete("+num+")'删除/a/li");var getImageSrc = getFullPath(imgObject); // 本地路径// 实例化image对象var pos = stIndexOf(".");var lastname = getImageSrc.substring(pos, getImageSrc.length) // 图片后缀if(lastname!=".jpg" lastname!=".png" lastname!=".jpeg" lastname!='.gif'){$("#a"+num).remove();alert("请选择一张图片");}else{ajaxFileUpload(num);$("#file0").unbind("change").bind("change",function (){clickUpload(num);});}num++;}function getFullPath(obj) { //得到图片的完整路径 if (obj) {if (erAgent.indexOf("MSIE") = 1) {obj.select();return document.selection.createRange().text; }else if (erAgent.indexOf("Firefox") = 1) { if (obj.files) {return obj.files.item(0).getAsDataURL();}return obj.value;}return obj.value;}}function ajaxFileUpload(num) {$.ajaxFileUpload({url: 'http://xxxx/updateImg', //用于文件上传的服务器端恳求地址secureuri: false, //是否需要平安协议,一般设置为falsefileElementId: 'file0', //文件上传域的IDdataType: 'json', //返回值类型一般设置为json success: function (data) //服务器胜利响应处理函数{var jsonText = data;console.log(jsonText);if(jsonText['status']==1){if(jsonText['info']!=""){console.log(jsonText['info']); $("#"+num).attr("src","__PUBLIC__//Admin/Upload/"+jsonText['info']);var images = $("#img").val();if(images!=""){$("#img").val(images+","+jsonText['info']);}else{$("#img").val(images+""+jsonText['info']);}}}else{$("#a"+num).remove();// alert("图片上传失败");}},error: function (data,e)//服务器响应失败处理函数{alert(e);}})}});以上就是本文的全部内容,盼望对大家学习php程序设计有所关心。
本文实例讲述了php简单实现批量上传图片的方法。
分享给大家供大家参考,具体如下:<?phpfunction upload_multi($path,$photo,$i){$uploaddir = './'.$path;//文件存放目录if(!file_exists($uploaddir))//如果目录不存在就新建$uploaddir=mkdir($uploaddir);$piece = explode('.',$photo['name'][$i]);$uploadfile = $uploaddir . '/'.md5($piece[0]).'.'.$piece[1];$result = move_uploaded_file($photo['tmp_name'][$i], $uploadfile);if(!$result){exit('上传失败');}return basename($uploadfile);}if($_POST['tijiao']){extract($_POST);$i=0;foreach ($_FILES["pictures"]["error"] as $key => $error) {if ($error == UPLOAD_ERR_OK) {upload_multi($email,$_FILES["pictures"],$i);}$i++;}}?><script language="javascript">function go_up(){document.getElementById('new_up').innerHTML+='<input type="file" name="pictures[]" /><br>';}</script><form action="index.php" method="post" enctype="multipart/form-data"><p>多图片上传</p><br><input type="file" name="pictures[]" /><br><div id="new_up"></div><input type="button"" name="add_img" value="新增上传" onclick="go_up()"/><br><input type="submit" value="Send" name="tijiao"/><br></form>希望本文所述对大家PHP程序设计有所帮助。
PHP多文件(图片)上传总共三个文件conn.php index.php upload.phpconn.php 文件--------------------------------------------------------------------------------------------------------------<?php$conn=mysql_connect("localhost","root","passwd") or die("数据库服务器连接错误".mysql_error());mysql_select_db("database",$conn) or die("数据库访问错误".mysql_error());mysql_query("set character utf8");mysql_query("set names utf8");?>index.php 文件--------------------------------------------------------------------------------------------------------------<html><head>上传文件</head><body><form method="post" action="upload.php" enctype="multipart/form-data"> <input name='uploads[]' type="file" multiple><input type="submit" name="uploadpic" value="上传"></form></body></html>upload.php 文件<?phpinclude("conn.php");$uploadfile; // 图片的名字if($_POST['uploadpic']=='上传'){$dest_folder = "picture/"; //上传图片保存的路径图片放在跟你upload.php同级的picture文件夹里$arr=array(); //定义一个数组存放上传图片的名称方便你以后会用的。
jquery批量上传图片+缩略图+水印图片上传+缩略图+水印处理代码://文件上传Public function _upload( $thumb = false , $thumbWidth = '' , $thumbHeight = '') {$upload = new \Think\Upload();// 实例化上传类$upload->maxSize = 3145728 ;// 设置附件上传大小$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型$upload->savePath = '/' . CONTROLLER_NAME .'/'; // 设置附件上传目录$info = $upload->upload();if(!$info) {return array('status' =>0, 'info'=> $upload->getError() );}else{if( $thumb ) { //生成缩略图$image = new \Think\Image();foreach($info as $file) {$thumb_file = './Uploads/' . $file['savepath'] . $file['savename'];$save_path = './Uploads/' .$file['savepath'] . 'mini_' . $file['savename'];$image->open( $thumb_file )->text('德兴房产','./data/1.otf',30,'#A7AAA4',\Think\Image::IMAGE_WATER_SOUTHWEST)->save( $thumb_file ); $image->open( $thumb_file )->text('德兴房产','./data/1.otf',24,'#A7AAA4',\Think\Image::IMAGE_WATER_SOUTHWEST)->thumb( $thumbWidth, $thumbHeight )->save( $save_path );return array('status' => 1,'savepath' => $file['savepath'],'savename' => $file['savename'],'pic_path' => $file['savepath'] . $file['savename'],'mini_pic' => $file['savepath'] . 'mini_' .$file['savename']);}}else{foreach($info as $file) {return array('status' => 1,'savepath' => $file['savepath'],'savename' => $file['savename'],'pic_path' => $file['savepath'].$file['savename']);}}}}前端主要代码(参考:///code/151.html):<div class="tab-pane" id="tab3"><div class="row"><div class="col-md-12"><div class="tab-pane"><div class="form-group"><input type="file" id="upload" class="form-control input-medium" /></div><div style="width:100%; float:left;padding:10px 20px 20px; background-color:#ccc"><p><ul class="imagelist" id="image_result"></ul></p></div></div></div></div></div> <!-- END #TAB3 --><div class="margin-top-10"><button type="submit" class="btn green ajax-post">确认</button><a href="javascript:" onclick="javascript:history.back(-1);return false;" class="btn default">返回</a></div></div></div></form></div></div></block><block name="foot"><link href="__PUBLIC__/assets/plugins/uploadify/uploadify.css" rel="stylesheet" type="text/css"/><link href="__PUBLIC__/assets/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/><script src="__PUBLIC__/assets/plugins/uniform/jquery.uniform.min.js" type="text/javascript" ></script><script src="__PUBLIC__/assets/plugins/uploadify/jquery.uploadify.min.js" type="text/javascript" ></script><script type="text/javascript">$(function(){var sid = "{:session_id()}";$('#upload').uploadify({'swf':'__PUBLIC__/assets/plugins/uploadify/uploadify.swf','buttonText': '选择图片','formData': { 'session_id':sid},'uploader': "{:U('uploadPic')}",'fileTypeDesc':'Image File','fileTypeExts':'*.jpg; *.jpeg; *.gif; *.png','auto' : true,'removeCompleted': false,onUploadSuccess: function(file, data, response) {$('#progress').hide();var result = $.parseJSON(data);//错误处理。
php多图片上传的简单例子php多图片上传的简单例子php 多图片上传的简单例子,只为初学的朋友参考,就跟随店铺一起去了解下吧,想了解更多相关信息请持续关注我们店铺!1、图片上传前台页面 upload.html注意input type=file 和enctype="multipart/form-data",这是php文件上传的关键。
a href=/wb/php/ target=_blank class=infotextkeyphp/a 多图片上传的前台页面2、处理多文件上传的程序 do_upload.phpphp 多图片上传的程序代码以下演示具体的上传过程:step1:上传图片step2:上传图片步骤二上传图片步骤三:上传图片成功在实际的测试过程中,提示所以图片上传失败,登录linux服务器,对files目录赋予可写入的权限即可。
如下图所示:给目录赋权限附:有关php的$_FILES数组$_FILES数组内容如下:$_FILES['myFile']['name'] 客户端文件的`原名称。
$_FILES['myFile']['type'] 文件的MIME 类型,需要浏览器提供该信息的支持,例如"image/gif"。
$_FILES['myFile']['size'] 已上传文件的大小,单位为字节。
$_FILES['myFile']['tmp_name'] 文件被上传后在服务端储存的临时文件名,一般是系统默认。
可以在php.ini的upload_tmp_dir 指定,但用 putenv() 函数设置是不起作用的。
$_FILES['myFile']['error'] 和该文件上传相关的错误代码。
['error'] 是在PHP 4.2.0 版本中增加的。
FileUploadServlet .java -----实现图片的储存package com.xiaoxing.upload;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.UUID;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import mons.fileupload.FileItem;import mons.fileupload.disk.DiskFileItemFactory;import mons.fileupload.servlet.ServletFileUpload;/*** <h1>Apache Fileupload文件上传(2014-5-3)</h1>* <p>* 1、如果你对本示例感兴趣并想了解更多,欢迎加入Java私塾在线学习社区(329232140)* </p>* <p>* 2、针对这个例子小修小改便可移植到你的实际项目中。
* </p>*/public class FileUploadServlet extends HttpServlet {private static final long serialVersionUID = 7579265950932321867L;// 设置文件默认上传目录(如果你没有在web.xml中配置的话)private String uploadDir = "c:/"; // 文件上传目录private String tempUploadDir = "c:/"; // 文件临时存放目录(会话销毁后由监听器自动删除)/** (non-Javadoc)** @see javax.servlet.GenericServlet#init()* 如果在web.xml中配置了文件上传目录则优先使用,判断文件目录是否存在,不存在就创建。
php中使用jqueryuploadify进行多图片上传实例php中使用jquery uploadify进行多图片上传实例导语:jquery uploadify是一款Ajax风格的'批量图片上传插件,在PHP中使用jquery uploadify很方便,请按照本文介绍的方法和步骤,为你的PHP程序增加jquery uploadify插件的批量上传图片功能。
下面的是店铺为大家搜集的在php中使用jquery uploadify进行多图片上传实例,希望对大家能有所帮助。
本文是以dilicms为基础,为其增加图片上传功能。
1.增加数据表dili_fieldtypes新字段:k=>image,V=>图片上传区域(VACHAR);2.修改application/libraries/dili/Field_behavior.php,在switch中增加如下代码:1case 'image':2$field=array(3'type'=>'VARCHAR',4'constraint'=>255,5'default'=>' '6);7break;3. 修改application/libraries/dili/Form.php 并且增加如下代码:1function _image($fileld,$default){2//$type= 'type=hidden';3//$width=($field['width'] ? $field['width'] : '570') .'px;';4//$height=($field['height'] ? $field['height'] : '415') .'px;';5return ;6}4.在content_form.php和category_content_form.php中增加判断代码:0102 if($v['type']=="image"):03?>04050607上传08取消上传0910" value=""/>11" value=""/>12asset/js/uploadify/uploadify.css" type="text/css" rel="stylesheet" />1314426. 新建photo.php文件:0102if ( ! defined('BASEPATH')) exit('No direct script access allowed');03date_default_timezone_set('Asia/Shanghai');04class Photo extends Front_Controller{05 public function __construct()06 {07 parent::__construct();08 }09 function _getFilePath()10 {11 $path="attachments/".date("Y")."/";12 if(!file_exists($path)){13 mkdir($path,'777');15 $path.=date("m")."/";16 if(!file_exists($path)){17 mkdir($path,'777');18 }19 return $path;20 }21 function _creat_photothumbs($FileName,$setW){22 $IMGInfo= getimagesize($FileName);23 if(!$IMGInfo) return false;24 if($IMGInfo['mime']== "image/pjpeg" || $IMGInfo['mime']=="image/jpeg"){25 $ThisPhoto= imagecreatefromjpeg($FileName);26 }elseif($IMGInfo['mime']== "image/x-png" || $IMGInfo['mime']== "image/png"){27 $ThisPhoto= imagecreatefrompng($FileName);28 }elseif($IMGInfo['mime']== "image/gif"){29 $ThisPhoto=imagecreatefromgif($FileName);30 }31 $width=$IMGInfo['0'];32 $height=$IMGInfo['1'];33 $scale=$height/$width;34 $nw=$setW;35 $nh=$nw*$scale;36 $NewPhoto=imagecreatetruecolor($nw,$nh);37imagecopyresampled($NewPhoto,$ThisPhoto,0,0,0,0,$nw,$nh,$ width,$height);38 ImageJpeg ($NewPhoto,$FileName);39 return true;41 function _savephoto_post(){42 $dest_dir =$this->_getFilePath();43 if (!empty($_FILES)) {44 $date = date('Ymd');45 //$dest_dir =$this->_getFilePath();46 $photoname = $_FILES["Filedata"]['name'];47 $phototype = $_FILES['Filedata']['type'];48 $photosize = $_FILES['Filedata']['size'];49 $fileInfo=pathinfo($photoname);50 $extension=$fileInfo['extension'];51 $newphotoname = date("YmdHis").mt_rand(10000,99999).'.'.$extension;52 $dest=$dest_dir.$newphotoname;53 //move_uploaded_file($_FILES['Filedata']['tmp_name'], iconv("UTF-8","gb2312",$dest));54 move_uploaded_file($_FILES['Filedata']['tmp_name'], $dest);55 //chmod($dest, 0755);56 //如果宽度大于600则要进行裁剪57 $arr=getimagesize($dest);58 if($arr[0]>600){59 $thumb_w=600;60 $this->_creat_photothumbs($dest,$thumb_w);61 }62 //生成缩略图63 $config2['image_library'] = 'gd2';64 $config2['source_image'] = $dest;65 $config2['create_thumb'] = TRUE;66 $config2['maintain_ratio'] = TRUE;67 $config2['width'] = 170;68 $config2['height'] = 150;69 $config2['master_dim']="width";70 $config2['thumb_marker']="_1";71 $this->load->library('image_lib', $config2);72 $this->image_lib->resize();73 echo $dest;74 }75 }76}77?>下载全文。
PHP图片批量上传代码-PHP技术-源码之家-源码学院PHP图片批量上传代码2010-08-02 14:09:23 来源:源码之家站长整理【大中小】浏览: 510 次<?php$zpass='123456'; //登陆密码$zurl=''; //使用地址$zname='upimage.php'; //本页面名称functionimageWaterMark($groundImage,$waterPos=0,$waterImage="", $waterText="",$textFont=5,$textColor="#FF0000"){$isWaterImage = FALSE;$formatMsg = "暂不支持该文件格式,请用图片处理软件将图片转换为GIF、JPG、PNG格式。
";//读取水印文件if(!empty($waterImage) && file_exists($waterImage)){$isWaterImage = TRUE;$water_info = getimagesize($waterImage);$water_w = $water_info[0];//取得水印图片的宽$water_h = $water_info[1];//取得水印图片的高switch($water_info[2])//取得水印图片的格式{case 1:$water_im = imagecreatefromgif($waterImage);break;case 2:$water_im = imagecreatefromjpeg($waterImage);break;case 3:$water_im = imagecreatefrompng($waterImage);break;default:die($formatMsg);}}//读取背景图片if(!empty($groundImage) && file_exists($groundImage)){$ground_info = getimagesize($groundImage);$ground_w = $ground_info[0];//取得背景图片的宽$ground_h = $ground_info[1];//取得背景图片的高switch($ground_info[2])//取得背景图片的格式{case 1:$ground_im = imagecreatefromgif($groundImage);break;case 2:$ground_im = imagecreatefromjpeg($groundImage);break;case 3:$ground_im = imagecreatefrompng($groundImage);break;default:die($formatMsg);}}else{die("需要加水印的图片不存在!");}//水印位置if($isWaterImage)//图片水印{$w = $water_w;$h = $water_h;$label = "图片的";}else//文字水印{$temp = imagettfbbox(ceil($textFont*2.5),0,"./cour.ttf",$waterText);//取得使用 TrueType 字体的文本的范围$w = $temp[2] - $temp[6];$h = $temp[3] - $temp[7];unset($temp);$label = "文字区域";}if( ($ground_w<$w) || ($ground_h<$h) ){echo "需要加水印的图片的长度或宽度比水印".$label."还小,无法生成水印!";return;}switch($waterPos){case 0://随机$posX = rand(0,($ground_w - $w));$posY = rand(0,($ground_h - $h));break;case 1://1为顶端居左$posX = 0;$posY = 0;break;case 2://2为顶端居中$posX = ($ground_w - $w) / 2; $posY = 0;break;case 3://3为顶端居右$posX = $ground_w - $w; $posY = 0;break;case 4://4为中部居左$posX = 0;$posY = ($ground_h - $h) / 2; break;case 5://5为中部居中$posX = ($ground_w - $w) / 2; $posY = ($ground_h - $h) / 2; break;case 6://6为中部居右$posX = $ground_w - $w; $posY = ($ground_h - $h) / 2; break;case 7://7为底端居左$posX = 0;$posY = $ground_h - $h; break;case 8://8为底端居中$posX = ($ground_w - $w) / 2;$posY = $ground_h - $h;break;case 9://9为底端居右$posX = $ground_w - $w-6;$posY = $ground_h - $h-6;break;default://随机$posX = rand(0,($ground_w - $w));$posY = rand(0,($ground_h - $h));break;}//设定图像的混色模式imagealphablending($ground_im, true);if($isWaterImage)//图片水印{imagecopy($ground_im, $water_im, $posX, $posY, 0, 0, $water_w,$water_h);//拷贝水印到目标文件}else//文字水印{if( !empty($textColor) && (strlen($textColor)==7) ){$R = hexdec(substr($textColor,1,2));$G = hexdec(substr($textColor,3,2));$B = hexdec(substr($textColor,5));}else{die("水印文字颜色格式不正确!");}imagestring ( $ground_im, $textFont, $posX, $posY, $waterText, imagecolorallocate($ground_im, $R, $G, $B));}//生成水印后的图片@unlink($groundImage);switch($ground_info[2])//取得背景图片的格式{case 1:imagegif($ground_im,$groundImage);break;case 2:imagejpeg($ground_im,$groundImage);break;case 3:imagepng($ground_im,$groundImage);break;default:die($errorMsg);}//释放内存if(isset($water_info)) unset($water_info);if(isset($water_im)) imagedestroy($water_im);unset($ground_info);imagedestroy($ground_im);}><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>图片上传</title><style type="text/css"><!--body, table {font-family: "宋体";font-size: 14px;padding:0px;margin:0px;}--></style></head><body><table width="760" border="0" align="center"><tr><td><?php//当前时间$nowtime=time();$baseurl= $_SERVER['PHP_SELF'] ? dirname($_SERVER['PHP_SELF']) : dirname($_SERVER['SCRIPT_NAME']);$baseurl='http://'.$_SERVER['HTTP_HOST'].$baseurl;//检查是否有提交图片if(!empty($_FILES['attachfile']['name'])){//处理每个图片foreach($_FILES['attachfile']['name'] as $k=>$v){//图片名字不为空if(!empty($v)){//后缀必须是图片名if(eregi("\.(gif|jpg|jpeg|png|bmp)$",$v)){//图片不能大于8Mif($_FILES['attachfile']['size'][$k] > 8388608) jieqi_delfile($_FILES['attachfile']['tmp_name'][$k]);else{//解析图片后缀$tmpary=explode('.', $v);$postfix=$tmpary[count($tmpary)-1];$attachdir = date('Ym',$nowtime);if (!file_exists($attachdir)) jieqi_createdir($attachdir);$attachdir .= '/'.date('d',$nowtime);if (!file_exists($attachdir)) jieqi_createdir($attachdir);$runtime = explode(' ', microtime());$attachname=$attachdir.'/'.date('His',$nowtime).round($run time[0]*1000).$k.'.'.$postfix;@move_uploaded_file($_FILES['attachfile']['tmp_name'][$k], $attachname);@chmod($attachname, 0644);$url=jieqi_htmlstr($baseurl.'/'.$attachname);//打水印if ($_REQUEST["water"]) {$pic=$attachname;$wpic="xhxsw.gif";$info=getimagesize($pic);$w=$info[0];$h=$info[1];if ($h>140) {imageWaterMark($pic,1,"xhxsw.gif");}if ($h>400) {imageWaterMark($pic,7,"xhxsw.gif");}if ($h>1600) {imageWaterMark($pic,4,"xhxsw.gif");}}echo '<a href="'.$url.'" target="_blank">'.$url.'</a>';><span title="复制图片URL到剪贴板" onclick="setcopy('<?echo $url?>', '图片地址已经复制到剪贴板')">[复制]</span><br><? }}else{jieqi_delfile($_FILES['attachfile']['tmp_name'][$k]);}}}}function jieqi_htmlstr($str, $quote_style=ENT_QUOTES){$str = htmlspecialchars($str, $quote_style);$str = nl2br($str);$str = str_replace(" ", " ", $str);return $str;}// 读文件function jieqi_readfile($file_name){if (function_exists("file_get_contents")) {return file_get_contents($file_name);}else{$filenum = @fopen($file_name, "rb");@flock($filenum, LOCK_SH);$file_data = @fread($filenum, @filesize($file_name));@flock($filenum, LOCK_UN);@fclose($filenum);return $file_data;}}//写文件function jieqi_writefile($file_name, &$data, $method = "wb"){$filenum = @fopen($file_name, $method);if(!$filenum) return false;@flock($filenum, LOCK_EX);$ret = @fwrite($filenum, $data);@flock($filenum, LOCK_UN);@fclose($filenum);@chmod($file_name, 0777);return $ret;}//删除文件function jieqi_delfile($file_name){return unlink($file_name);}// 删除目录function jieqi_delfolder($dirname, $flag = true){$handle = @opendir($dirname);while ($file = @readdir($handle)) {if($file != '.' && $file != '..'){if (is_dir($dirname . DIRECTORY_SEPARATOR . $file)){jieqi_delfolder($dirname . DIRECTORY_SEPARATOR . $file, true);}else{@unlink($dirname . DIRECTORY_SEPARATOR . $file);}}}@closedir($handle);if ($flag) @rmdir($dirname);}//建立目录function jieqi_createdir($dirname, $mode=0777, $recursive = false){if (version_compare(PHP_VERSION, '5.0.0', '>=')) {return mkdir($dirname, $mode, $recursive);}if (!$recursive) {$ret=mkdir($dirname, $mode);if($ret) chmod($dirname, $mode);return $ret;}return is_dir($dirname) or (jieqi_createdir(dirname($dirname), $mode, true) and mkdir($dirname, $mode));}//检查目录是否存在,不存在尝试自动建立function jieqi_checkdir($dirname, $autocreate=0){if(is_dir($dirname)){return true;}else{if(empty($autocreate)) return false;else return jieqi_createdir($dirname);}}></td></tr></table><?if ($_GET[z]=$zpass){?><table width="760" border="0" align="center"><tr><td colspan="2" align="right"><form action="<?echo $zname?>" ><input type="submit" name="quit" value=" 退出"></form></td></tr></table><form name="frmupload" method="post" action="<?echo $zname?>?z=<?echo $zpass?>" enctype="multipart/form-data"> <table width="760" border="1" align="center"><tr><td colspan="2" align="center">图片批量上传程序</td></tr><td width="114">图片一:</td><td width="470"><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><tr><td>图片二:</td><td><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><tr><td>图片三:</td><td><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><tr><td>图片四:</td><td><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><tr><td>图片五:</td><td><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><tr><td>图片六:</td><td><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><td>图片七:</td><td><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><tr><td>图片八:</td><td><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><tr><td>图片九:</td><td><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><tr><td>图片十:</td><td><input type='file' class='text' size='60' name='attachfile[]' id='attachfile[]' /></td></tr><tr><input name="water" type="hidden" id="water" value="0" checked ></tr><tr><td> </td><td width=600><input type="submit" name="Submit" value=" 提交 "></form></td></tr></table><table width="760" border="0" align="center"><tr><td><?phpif(!empty($_REQUEST['delurl'])){foreach($_REQUEST['delurl'] as $v){if(empty($v)) continue;if(!eregi("\.(gif|jpg|jpeg|png|bmp)$",$v)){echo '<font color="red">您提交的不是图片地址:</font><a href="'.urlencode($v).'" target="_blank">'.$v.'</a><br>';}elseif(strpos($v,$baseurl) !== 0){echo '<font color="red">您提交的图片地址错误:</font><a href="'.urlencode($v).'" target="_blank">'.$v.'</a><br>';}else{$delpath=str_replace($baseurl,'.',$v);if(!file_exists($delpath)){echo '<font color="red">图片不存在:</font><a href="'.urlencode($v).'" target="_blank">'.$v.'</a><br>';}else{$ret=jieqi_delfile($delpath);if($ret) echo '<font color="blue">删除完成:</font><a href="'.urlencode($v).'" target="_blank">'.$v.'</a><br>';else echo '<font color="red">删除失败,可能权限不对:</font><a href="'.urlencode($v).'" target="_blank">'.$v.'</a><br>';}}}}></td></tr></table><script type="text/java script">function setcopy(text, alertmsg){clipboardData.setData('Text', text);alert(alertmsg);}</script><?php$b=0;$dir = './../uppic';echo "<center>已经上传的图片如下:\n<div style='width:830px'>";function view_dir($directory){$handle = opendir( $directory );while ( $file = readdir($handle) ){$bdir = $directory . '/' .$file ;if ($file <> '.' && $file <> '..' && $file <> 'Thumbs.db' && $file <> $zname && is_dir($bdir)){view_dir( $directory .'/'. $file);}else if( $file <> '.' && $file <> '..' && $file <> 'Thumbs.db' && $file <> $zname){$a = $file ;><div style='float:left;width:180px;' id=<?echo $b?> name=<?echo $b?>><a href='<?echo $directory?>/<?echo $a?>' target=_blank><?echo $a?></a><span title="复制图片URL到剪贴板" onclick="setcopy('http://<?echo $zurl?>/1/2/.<?echo $directory?>/<?echo $a?>', '图片地址已经复制到剪贴板')">[复制]</span></div><? $b=$b+1;}}closedir( $handle );}view_dir($dir);><form name="frmdelete" action="<?echo $zname?>?z=<?echo $zpass?>" method="post"><table width="760" border="1" align="center"cellpadding="3"><tr><td colspan="2" align="center">删除图片</td></tr><tr><td width="114">图片网址一:</td><td width="470"><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td>图片网址二:</td><td><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td>图片网址三:</td><td><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td>图片网址四:</td><td><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td>图片网址五:</td><td><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td>图片网址六:</td><td><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td>图片网址七:</td><td><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td>图片网址八:</td><td><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td>图片网址九:</td><td><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td>图片网址十:</td><td><input name="delurl[]" id="delurl[]" type="text" size="60"></td></tr><tr><td></td><td><input type="submit" name="Submit2" value=" 删除"></td></tr></table></form><?}else{?><br><br><br><center>请输入密码:<form action="<?echo $zname?>" method="get"><input type=password name=z size=12><input type=submit value=" 提交 "></form><?}?></body></html>。
jquery实现上传图⽚功能本⽂实例为⼤家分享了jquery实现上传图⽚功能的具体代码,供⼤家参考,具体内容如下代码:<!DOCTYPE html><html><head><meta charset="UTF-8"><title>点击头像上传图⽚</title><style>*{margin:0;padding: 0;}div,#avarimgs,#xdaTanFileImg{width: 100px;height: 100px;}div{margin:50px auto;position: relative;}#xdaTanFileImg{position: absolute;top: 0;left: 0;opacity: 0;}</style></head><body><div><input type="file" name="pclogo" id="xdaTanFileImg" onchange="xmTanUploadImg(this)" accept="image/*"><img src="/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3787285033,4172246344&fm=26&gp=0.jpg" class="img-circle img-thumbnail img-responsive" id="avarimgs"> </div></body><script src="/jquery-2.1.1.min.js"></script><script type="text/javascript">if (typeof FileReader == 'undefined') {document.getElementById("xmTanDiv").InnerHTML = "<h1>当前浏览器不⽀持FileReader接⼝</h1>";document.getElementById("xdaTanFileImg").setAttribute("disabled", "disabled");}//选择图⽚,马上预览function xmTanUploadImg(obj) {console.log(obj)var file = obj.files[0];console.log(obj);console.log(file);console.log("file.size = " + file.size);var reader = new FileReader();reader.onloadstart = function (e) {console.log("开始读取....");}reader.onprogress = function (e) {console.log("正在读取中....");}reader.onabort = function (e) {console.log("中断读取....");}reader.onerror = function (e) {console.log("读取异常....");}reader.onload = function (e) {console.log("成功读取....");var img = document.getElementById("avarimgs");img.src = e.target.result;//或者 img.src = this.result; //e.target == this}reader.readAsDataURL(file)}</script></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
很多时候在做完自己的是以后都喜欢来园子里面看看,但多数时候是学习,今天闲来之于也学学写点东西今天在公司做一个上传图片的东西于是就在gg上找了一个php+swf上传的东西没有办法公司用的是.net于是就动手改动了代码<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http:// /TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml" ><head runat="server"><title>无标题页</title><style>.swiff-uploader-box a {display: none !important;}/* .hover simulates the flash interactions */a:hover, a.hover {color: red;}#demo-status {padding: 10px 15px;width: 420px;border: 1px solid #eee;}#demo-status .progress {background: url(progress.gif) no-repeat;background-position: +50% 0;margin-right: 0.5em;vertical-align: middle;}#demo-status .progress-text {font-size: 0.9em;font-weight: bold;}#demo-list {list-style: none;width: 450px;margin: 0;}#demo-list li.validation-error {padding-left: 44px;display: block;clear: left;line-height: 40px;color: #8a1f11;cursor: pointer;border-bottom: 1px solid #fbc2c4;background: #fbe3e4 url(failed.png) no-repeat 4px 4px;}#demo-list li.file {border-bottom: 1px solid #eee;background: url(file.png) no-repeat 4px 4px;overflow: auto;}#demo-list li.file.file-uploading {background-image: url(uploading.png);background-color: #D9DDE9;}#demo-list li.file.file-success {background-image: url(success.png);}#demo-list li.file.file-failed {background-image: url(failed.png);692}#demo-list li.file .file-name {font-size: 1.2em;margin-left: 44px;display: block;clear: left;line-height: 40px;height: 40px;font-weight: bold;}#demo-list li.file .file-size {font-size: 0.9em;line-height: 18px;float: right;margin-top: 2px;margin-right: 6px;}#demo-list li.file .file-info {display: block;margin-left: 44px;font-size: 0.9em;line-height: 20px;clear}#demo-list li.file .file-remove {clear: right;float: right;line-height: 18px;margin-right: 6px;}</style><script type="text/javascript" src="mootools.js"></script><script type="text/javascript" src="Swiff.Uploader.js"></script><script type="text/javascript" src="Fx.ProgressBar.js"></script><script type="text/javascript" src="Lang.js"></script>693<script type="text/javascript" src="FancyUpload2.js"></script><script type="text/javascript">/* <![CDATA[ *//*** FancyUpload Showcase** @license MIT License* @author Harald Kirschner <mail [at] digitarald [dot] de>* @copyright Authors*/window.addEvent('domready', function() { // wait for the content// our uploader instancevar up = new FancyUpload2($('demo-status'), $('demo-list'), { // op tions object// we console.log infos, remove that in production!!verbose: true,// url is read from the form, so you just have to change one pl aceurl: $('form-demo').action,// path to the SWF filepath: 'Swiff.Uploader.swf',// remove that line to select all files, or edit it, add more i temstypeFilter: {'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.g if; *.png'},// this is our browse button, *target* is overlayed with the Fl694ash movietarget: 'demo-browse',// graceful degradation, onLoad is only called if all went wel l with FlashonLoad: function() {$('demo-status').removeClass('hide'); // we show the actua l UI$('demo-fallback').destroy(); // ... and hide the plain for m// We relay the interactions with the overlayed flash to th e linkthis.target.addEvents({click: function() {return false;},mouseenter: function() {this.addClass('hover');},mouseleave: function() {this.removeClass('hover');this.blur();},mousedown: function() {this.focus();}});// Interactions for the 2 other buttons$('demo-clear').addEvent('click', function() {up.remove(); // remove all filesreturn false;});695$('demo-upload').addEvent('click', function() {up.start(); // start uploadreturn false;});},// Edit the following lines, it is your custom event handling/*** Is called when files were not added, "files" is an array of invalid File classes.** This example creates a list of error elements directly in th e file list, which* hide on click.*/onSelectFail: function(files) {alert(files);files.each(function(file) {new Element('li', {'class': 'validation-error',html: file.validationErrorMessage || file.validatio nError,title: ng.get('FancyUpload', 'removeTitl e'),events: {click: function() {this.destroy();}}}).inject(this.list, 'top');}, this);},/*** This one was directly in FancyUpload2 before, the event make696s it* easier for you, to add your own response handling (you proba bly want* to send something else than JSON or different items).*/onFileSuccess: function(file, response) {var json = new Hash(JSON.decode(response, true) || {});if (json.get('status') == '1') {file.element.addClass('file-success');.set('html', '<strong>Image was uploaded:</str ong> Width:' + json.get('width') + 'px, Height:' + json.get('height') + 'px, <em>Mime:' + json.get('mime') + '</em>');//alert(response);} else {file.element.addClass('file-failed');//alert(response);.set('html', '<strong>An error occured:</stron g> ' + (json.get('error') ? (json.get('error') + ' #' + json.get('code ')) : response));}},/*** onFail is called when the Flash movie got bashed by some bro wser plugin* like Adblock or Flashblock.*/onFail: function(error) {switch (error) {case'hidden': // works after enabling the movie and cl icking refreshalert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');break;case'blocked': // This no *full* fail, it works afte697r the user clicks the buttonalert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');break;case'empty': // Oh oh, wrong pathalert('A required file was not found, please be pat ient and we fix this.');break;case'flash': // no flash 9+ :(alert('To enable the embedded uploader, install th e latest Adobe Flash plugin.')}}});});/* ]]> */</script></head><body><div id="demo"><form action="script.aspx" method="post" enctype="multipart/form-data " id="form-demo"><fieldset id="demo-fallback"><legend>File Upload</legend><p>This form is just an example fallback for the unobtrusive b ehaviour of FancyUpload.If this part is not changed, something must be wrong with y our code.</p><label for="demo-photoupload">Upload a Photo:698<input type="file" name="Filedata" /></label></fieldset><div id="demo-status"class="hide"><p><a href="#" id="demo-browse">选择图片</a> |<a href="#" id="demo-clear">清除图片</a> |<a href="#" id="demo-upload">开始上传</a></p><div><strong class="overall-title"></strong><br /><img src="bar.gif"class="progress overall-progress" /></div><div><strong class="current-title"></strong><br /><img src="bar.gif"class="progress current-progress" /></div><div class="current-text"></div></div><ul id="demo-list"></ul></form></div></body></html>这里是前台的后台处理图片如下代码if (Request.Files.Count != 0){HttpFileCollection fc = Request.Files;699for (int i = 0; i < fc.Count; i++){try{object s = fc[i];System.Web.HttpPostedFile pf = (System.Web.HttpPost edFile)s;pf.SaveAs(Server.MapPath("pic/" + pf.FileName));//Image img=new Image( );//img.ImageUrl = Server.MapPath("pic/" + pf.FileNam e);//img.Width//Response.Write("{\"width\":\"10249\",\"height\":\ "51\",\"mime\":\"42.4000\"}");Response.Write("{\"status\":\"1\",\"name\":\"\",\"h ash\":\"\",\"width\":250,\"height\":12,\"mime\":\"image\"}");}catch{Response.Write("{\"status\":\"1\",\"name\":\"\",\"h ash\":\"\",\"width\":250,\"height\":12,\"mime\":\"image\"}");}}}else{string s = "something wrong";}好了这里就处理完了应该来说还是很有效果图:7007013702。
jQuery+PHP实现图⽚上传并提交功能图⽚上传思路:通过ajax实现图⽚上传,然后把PHP返回的图⽚地址,加⼊到隐藏字段中,最后通过表单提交给后台PHP,代码如下HTML代码 zimg.html⽂件:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>⾃定义上传图⽚</title></head><body><form action="a.php?action=2" method="post"><span>上传图⽚</span><span><input type="file" id="img_url" name="img_url" accept=".jpg, .gif, .jpeg, .bmp, .png"/><a onclick="UpLoadImg()">上传</a><input type="hidden" id="url_data" name="url_data"/></span><br><span><input type="submit" value="提交"></span></form></body><!-- 引⼊jq --><script src="https:///jquery-3.0.0.min.js"></script><script>function UpLoadImg(){//获取上传⽂件var formData = new FormData();formData.append('img_url', $('#img_url')[0].files[0]);console.log(formData)//提交后台处理$.ajax({url: 'a.php?action=1',type: 'POST',cache: false,data: formData,dataType: "JSON",processData: false,contentType: false}).done(function(res) {console.log(res.url);if(res.status == 1){//赋值给字段$('#url_data').val(res.url);alert(res.msg)}else{alert(res.msg)}}).fail(function(res) {});}</script></html>后台PHP代码 a.php:<?phpif($_GET['action'] == 1){//上传图⽚接⼝$img = $_FILES['img_url'];//获取上图⽚后缀$type = strstr($img['name'], '.');$rand = rand(1000, 9999);//命名图⽚名称$pics = date("YmdHis") . $rand . $type;//上传路径$pic_path = "img/". $pics;//移动到指定⽬录,上传图⽚$res = move_uploaded_file($img['tmp_name'], $pic_path);if($res){echo json_encode(['status' => 1, 'msg' => '上传成功','url' => $pic_path]);exit;}else{echo json_encode(['status' => 0, 'msg' => '上传失败']);exit;}}elseif($_GET['action'] == 2){//提交⽂件表单echo '<pre>';var_dump($_POST);}最后实现效果如下:ps:js代码是使⽤jQuery的写法,需引⼊jQuery代码库⽂件到此这篇关于jQuery加PHP实现图⽚上传并提交实现详解的⽂章就介绍到这了,更多相关jQuery加PHP实现图⽚上传并提交内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
php+ajax实现图⽚⽂件上传功能实例⽬前常⽤的异步⽂件上传功能有⼏种,⽐较多见的如使⽤iframe框架形式,ajax功能效果,以及flash+php功能,下⾯介绍ajax 与iframe实现异步⽂件上传的功能的例⼦。
其实就是实现⽆刷新式的⽂件上传。
可采⽤IFRAME⽂件上传原理。
实际上在⽤PHP上传⽂件时。
只能⽤$_FILES形式,但是若我们只是单⼀的⽤JS⽅式取其ID,如<input id='img'type='file'>..document.getElementById('img').value或者jquery形式的$("#img")都是不能正真实际上传的(但是还是有很多⼈这样做,刚开始时我也是)。
可是功能上⼜要要求实现所谓的“异步上传”,怎么办呢?只能借助于第三⽅的组件,或者⾃⼰写⼀个(在⽹页⾥嵌⼊⼀个IFRAME)。
但如果是考虑开发时间,建议⽤第三⽅的,这⾥有⼀个不错的jQuery 的Ajax⽂件上传的组件,即“ajaxfileupload.js",其组件下载地址为:过程:(1 )前端⽂件的代码: test.php复制代码代码如下:<script type="text/javascript" src="jquery.js"></script><script type="text/javascript" src="ajaxfileupload.js"></script><script type="text/javascript">function ajaxFileUpload(){$.ajaxFileUpload({url:'doajaxfileupload.php', //你处理上传⽂件的服务端secureuri:false,fileElementId:'img',dataType: 'json',success: function (data){alert(data.file_infor);}})return false;}</script>相应的HTML为:<input id="img" type="file" size="45" name="img" class="input"><button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>这样客户端就完成了。
php图⽚上传存储源码,可实现预览<?phpheader("content-Type: text/html; charset=gb2312");$uptypes=array('image/jpg', //上传⽂件类型列表'image/jpeg','image/png','image/pjpeg','image/gif','image/bmp','application/x-shockwave-flash','image/x-png','application/msword','audio/x-ms-wma','audio/mp3','application/vnd.rn-realmedia','application/x-zip-compressed','application/octet-stream');$max_file_size=10000000; //上传⽂件⼤⼩限制, 单位BYTE$path_parts=pathinfo($_SERVER['PHP_SELF']); //取得当前路径$destination_folder="up/"; //上传⽂件路径$watermark=0; //是否附加⽔印(1为加⽔印,0为不加⽔印);$watertype=1; //⽔印类型(1为⽂字,2为图⽚)$waterposition=2; //⽔印位置(1为左下⾓,2为右下⾓,3为左上⾓,4为右上⾓,5为居中);$waterstring=""; //⽔印字符串$waterimg="xplore.gif"; //⽔印图⽚$imgpreview=1; //是否⽣成预览图(1为⽣成,0为不⽣成);$imgpreviewsize=1/1; //缩略图⽐例?><html xmlns="undefined"><head><title>图⽚上传储存</title><LINK rel="Bookmark" href="/ico.ico" ><LINK rel="Shortcut Icon" href="/ico.ico" /><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><meta name="description" content="亿脑⽹盘_免费⽹络⽆限⼤图⽚上传储存" /><style type="text/css">body,td{font-family:tahoma,verdana,arial;font-size:11px;line-height:15px;background-color:white;color:#666666;strong{font-size:12px;}a:link{color:#0066CC;}a:hover{color:#FF6600;}a:visited{color:#003366;}a:active{color:#9DCC00;}a{TEXT-DECORATION:none}td.irows{height:20px;background:url("index.php?i=dots") repeat-x bottom}</style></head><script type="text/javascript">function oCopy(obj){obj.select();js=obj.createTextRange();js.execCommand("Copy");};function sendtof(url){window.clipboardData.setData('Text',url);alert('复制地址成功,粘贴给你好友⼀起分享。
php多个文件及图片上传实例详解php多个文件及图片上传实例详解主要介绍了php多个文件及图片上传的方法,以实例形式详细叙述了多文件上传的原理与实现技巧,非常实用,需要的朋友可以参考下。
本文实例讲述了php多个文件及图片上传的方法。
分享给大家供大家参考。
具体实现方法如下:多个文件上传是在单文件上传的基础上利用遍历数组的方式进行遍历表单数组然后把文件一个个上传到服务器上了,下面就来看一个简单多个文件上传实例多个文件上传和单独文件上传的处理方式是一样的,只需要在客户端多提供几个类型为“file”的输入表单,并指定不同的“name”属性值。
例如,在下面的`代码中,可以让用户同时选择三个本地文件一起上传给服务器,客户端的表单如下所示:复制代码代码如下:<html><head><title>多个文件上传表单</title></head><body><form action="mul_upload.php" method="post" enctype="multipart/form-data"><input type="hidden" name="MAX_FILE_SIZE" value="1000000">选择文件1:<input type="file" name='myfile[]'><br>选择文件2:<input type="file" name='myfile[]'><br>选择文件3:<input type="file" name='myfile[]'><br><input type="submit" value="上传文件"></form></body></html>在上面的代码中,将三个文件类型的表单以数组的形式组织在一起。
简单的PHP多图上传⼩程序之前也写过很多图⽚上传的程序,但是都没有下⾯这个简短。
越简单的程序越好,不是吗?先上源代码,你可以copy到⾃⼰的电脑上去运⾏~<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><head><title>多⽂件上传</title></head><body><form accept="" method="post" enctype="multipart/form-data"><input type="file" name="img[]" /><br /><input type="file" name="img[]" /><br /><input type="file" name="img[]" /><br /><input type="file" name="img[]" /><br /><input type="file" name="img[]" /><br /><input type="file" name="img[]" /><br /><input type="submit" name="s" /><br /></form><?php//上传⽂件信息$img = $_FILES['img'];if ($img){//⽂件存放⽬录,和本php⽂件同级$dir = dirname(__file__);$i = 0;foreach ($img['tmp_name'] as $value){$filename = $img['name'][$i];if ($value){$savepath="$dir\\$filename";$state = move_uploaded_file($value, $savepath);//如果上传成功,预览if($state){echo "<img src='$filename' alt='$filename' /> ";}}$i++;}}?></body></html>move_uploaded_file() 函数move_uploaded_file() 函数将上传的⽂件移动到新位置。
这篇文章主要为大家详细介绍了php+flash+jQuery多图片上传实现源码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下flash+php多图片上传的源码,测试成功,一个经典的上传源码,为什么要用flash作为上传的组件呢,其实这里不仅仅是flash,另加了jquery的技术,这样做的目的是为了更好更方便的管理图片,使用过QQ空间进行上传图片的童鞋都知道,QQ空间的上传体验度很好,而且管理我们上传的图片非常的方便,使用的技术基本上就是flash与jquery技术了。
flash+jquery是作为前端图片上传展示的,还需要与php的结合才能将图片上传到指定的目标,这里的php一共有两个文件,一个upload.php 是上传的核心代码,index.php 便是整合flash+php+jquery 技术的结合,将提交上来的图片上传到目录upload 下面,另外还有一个文件夹images,这里面便是调用的upload.swf flash文件和jquery.js文件了,技术已经实现了,剩下便是怎样跟数据库进行整合就很简单了,这里不再详解了。
效果图:关键代码:upload.php<?php $uploaddir = 'upload/'; $filename = date("Ymdhis").rand(100,999); $uploadfile = $uploaddir . $filename.substr($_FILES['Filedata']["name"],strrpos($_FILES['Filedata']["name"],".")); $temploadfile = $_FILES['Filedata']['tmp_name']; move_uploaded_file($temploadfile , $uploadfile); //返回数据在页面上js做处理 $filedata = array( 'result' => 'true', 'name' => $_FILES['Filedata']["name"], 'filepath' => $uploadfile, ); echo json_encode($filedata); exit;index.php<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>swfupload</title><script src="images/jquery.js" type="text/javascript"></script><script> /*上传错误信息提示*/ function showmessage(message){alert(message);} /*显示文件名称*/ function setfilename(ID,filename){ ID = replaceStr(ID); var htmls = '<li id="'+ID+'"><p>'+filename+'</p><p class="load">0%</p></li>'; $("#uploadPut").append(htmls); } /*显示上传进度*/ function setfileload(ID,load){ ID = replaceStr(ID); $("#"+ID+" .load").html(load); } /*返回服务上传的数据*/ function setfilepath(ID,data){ ID = replaceStr(ID); var s = eval('('+data+')'); if(s.result=="true"){ $("#"+ID).html("<img id='"+s.id+"' src='"+s.filepath+"'/><br/>"+); }else{ $("#"+ID).html(+"上传失败"); } } /*替换特殊字符*/ function replaceStr(ID){ var reg = new RegExp("[=,/,\,?,%,#,&,(,),!,+,-,},{,:,>,<]","g"); //创建正则RegExp对象 var ID = ID.replace(reg,""); return ID; }</script></head><style> .main{ width:610px; height:0px auto; border:1px solid #e1e1e1; font-size:12px; padding:10px;} .main p{ line-height:10px; width:500px; float:right; text-indent:20px;} .uploadPut{ width:100%; clear:both;} ul,li{ margin:0px; padding:0px; list-style:none} .uploadPut li{width:120px; padding:10px; text-align:center; border:1px solid #ccc; overflow:hidden; background-color:#e1e1e1; line-height:25px; float:left; margin:5px} .uploadPut img{ width:120px; height:90px;}</style><body> <div class="main"> <?php //获取项目跟路径 $baseURL = 'http://' . $_SERVER ['SERVER_NAME'] . (($_SERVER['SERVER_PORT'] == 80) ? '' : ':' . $_SERVER ['SERVER_PORT']) . ((($path = str_ireplace('\\', '/', dirname ( $_SERVER ['SCRIPT_NAME'] ))) == '/') ? '' : $path); //设置swfupload参数 $flashvars = 'uploadURL=' . urlencode($baseURL . '/upload.php'); #上传提交地址 $flashvars.= '&buttonImageURL=' . urlencode($baseURL . '/images/upload.png'); #按钮背景图片 $flashvars.= '&btnWidth=95'; #按钮宽度 $flashvars.= '&btnHeight=35'; #按钮高度 $flashvars.= '&fileNumber=20'; #每次最多上传20个文件 $flashvars.= '&fileSize=200'; #单个文件上传大小为20M $flashvars.= '&bgColor=#ffffff'; #背景颜色 $flashvars.= '&fileTypesDescription=Images'; #选择文件类型 $flashvars.= '&fileType=*.jpg;*.png;*.gif;*.jpeg'; #选择文件后缀名 ?> <object style="float: left;" width="95" height="35" data="images/upload.swf" type="application/x-shockwave-flash"> <param value="transparent" name="wmode"> <param value="images/upload.swf" name="movie"> <param value="high" name="quality"> <param value="false" name="menu"> <param value="always" name="allowScriptAccess"> <param value="<?php echo $flashvars;?>" name="flashvars"> </object> <p>允许上传格式JPG, GIF, JEPG, PNG ,每个文件不超过20MB,一次可上传多20张!</p> <div class="uploadPut"> <ul id="uploadPut"> </ul> <div style="clear: both;"></div> </div> </div></body></html>其实这种组合的上传技术在许多大型的网站上面都有,更多的是应用在图片的管理上面,比如51 空间的图片管理,基本功能都是类似的,重要的一定要学习一下flash 与php 之间的通信技术,在大型的开发中,这种技术会经常出现的。