aws 上传webapp
2019-02-27 11:22:17 heaven0228 阅读数 28
var a=[{
    title:'拍照' 
},{ 
    title:'从手机相册选择' 
}]; 
plus.nativeUI.actionSheet({ 
    cancel:'取消', 
    buttons:a 
},function(b){ 
    switch(b.index){ 
        case 0: 
            break; 
        case 1: 
            //拍照 
            plus.camera.getCamera().captureImage(function(e){
                    plus.io.resolveLocalFileSystemURL(e, function(entry) {
                        plus.nativeUI.showWaiting( "正在加载图片..." );
                        var path = entry.toLocalURL()+'?version='+new Date().getTime();
                        //保存图片到相册中
                        plus.gallery.save( entry.toLocalURL(), function(){
                        	//保存成功执行
                        },function(){
                            mui.toast("图片保存到相册失败...");
                        } );
	            entry.file( function(file){  
	                 var reader = new plus.io.FileReader();
		    reader.onloadend = function() {
		        var imgpre = new Image();
		        imgpre.onload = function() {
			//压缩后的Base64
			var compressedDataUrl = compress(imgpre);
			//上传操作
			plus.nativeUI.closeWaiting();
		        };
		        imgpre.src = reader.result;
		    }
		    reader.readAsDataURL(file);
               	 });
                    }, function(e) {
                    	plus.nativeUI.closeWaiting();
                         mui.toast("读取拍照文件错误:" + e.message);
                    });
                });   
            break; 
        case 2: 
        	//本地相册
        	plus.gallery.pick(function(path){
	    plus.io.resolveLocalFileSystemURL(path,function(entry){                 
                 plus.nativeUI.showWaiting( "正在加载图片..." );
	        entry.file( function(file){  
		 var reader = new plus.io.FileReader();
		 reader.onloadend = function() {
		     var imgpre = new Image();
	                  imgpre.onload = function() {
		         //压缩后的Base64
		         var compressedDataUrl = compress(imgpre);		            
		         //上传操作
                                   plus.nativeUI.closeWaiting();
		      };
		      imgpre.src = reader.result;
		  }
		  reader.readAsDataURL(file);
	       });
                );
            });
            break; 
        default: 
            break; 
    } 
},false); 

压缩方法

//压缩方法
function compress(img) {
    var canvas=document.createElement("canvas"); 
	var width=img.width; 
	var height=img.height; 
    if(width>height){ 
       if(width>700){ 
          height=Math.round(height*=700/width); 
          width=700; 
       } 
	}else{ 
	   if(height>700){ 
	       width=Math.round(width*=700/height); 
	   } 
	   height=700; 
	} 
	canvas.width=width; 
	canvas.height=height; 
	var ctx=canvas.getContext('2d'); 
	ctx.drawImage(img,0,0,width,height); 
	 
	var dataUrl=canvas.toDataURL('image/jpeg',0.8); 
    return dataUrl.replace('data:image/jpeg;base64,',''); 
}

JAVA后台

byte[] bs = Base64Utils.decodeFromString(fileBase64);
Thumbnails.of(new ByteArrayInputStream(bs)).scale(1f).outputQuality(1f).outputFormat("jpg").toFile(filePath);  

 

2018-06-04 18:56:05 chenXiaoYu_csdn 阅读数 1693


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <title>title</title>
    <script src="../js/jquery-1.8.3.min.js"></script>
    <script src="../js/mui.min.js"></script>
    <script src="../js/common.js"></script>
    <script src="../js/common-path.js"></script>
    <script src="../js/mui.picker.min.js"></script>
    <script src="../js/mui.poppicker.js"></script>
    <script type="text/javascript" src="../../resources/js/x-util.js"></script>
    
    <script type="text/javascript" src="../js/exif.js"></script>
    
    <link href="../css/mui.min.css" rel="stylesheet"/>
    <link href="../css/mui.picker.css" rel="stylesheet"/>
    <link href="../css/mui.poppicker.css" rel="stylesheet"/>
    <link href="../css/common.css" rel="stylesheet"/>
    <style>
        body{
           background-color:#fff;
        }
        .pdtop{
            margin-top:0;
           border-top:10px solid #f0f0f0;
        }
        .mui-bar .mui-btn-nav.mui-pull-right {
            margin-right: 5px;
        }
        .changImg {
            width: 75px;
            height: 75px;
            margin: 5px;
            float: left;
        }
        
        #imgBox {
            padding-left: 5px;
            background: #fff;
            overflow: hidden;
        }
        #file {
            width: 75px;
            height: 75px;
            display: block;
            opacity: 0;
        }
        .disChangImg{
        	width: 75px;
            height: 75px;
            margin: 5px;
            float: left;
        }
    </style>

</head>
<body>

<header id="header" class="mui-bar mui-bar-nav">
    <button id="subBtn" class="mui-btn mui-btn-nav mui-pull-right submit" onclick="submitFeedback()">提交</button>
</header>
<div class="nrcount">
   
    <div class="pdtop">
        <form class="mui-input-group" style="" id="feedbackForm" enctype="multipart/form-data">
            <!-- 表单隐藏域 表单提交时传递的参数 start -->
            <input type="hidden" id="orientationStr" name="orientationStr"/>
             <!-- 表单隐藏域 表单提交时传递的参数 end -->
        </form>
        
        <!-- 图片上传 start 
        	 不放在form中的原因:每次选择或拍照后再次选择或拍照时,formdata都会清空只保留最后一次的信息,所以传到后台的永远是最后一张照片
        	 修改后每次选择或拍照时,通过type=file得到图片并存入数组中,最后将图片数组append到formdata中再传到后台去  
        -->
        <div class="mui-input-row upimg" style="background-color:#f0f0f0;">
	        <label>图片上传</label>
	        <span class="mui-pull-right">非必要项</span>
        </div>
        <div class="basicAvatar">
            <div id="imgBox">
                <div class="Upload button changImg" id="morFile">
                	<input type="file" id="file" class="up" multiple="8" name="file" accept="image/*">
                </div>
                <div class="Upload button disChangImg" id="disFile" style="display: none;" onclick="checkImgNum()">
                </div>
            </div>
        </div>
        <!-- 图片上传 end -->
    </div>
</div>

<script>
	$(function(){
		//判断是Android还是iOS
		var ua = navigator.userAgent.toLowerCase();
		var isiOS = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1);  // ios终端
		if(!isiOS){
			//input type="file"对一些Android手机来说(如华为)并不能调用拍照功能 加上如下代码可调用手机摄像头
		     $("input").attr('capture','camera');
		}
	})

	//删除数组中某一元素
	function removeArrObj(_arr,_obj){
	    var length = _arr.length;
	    for(var i = 0; i < length; i++){
	        if(_arr[i] == _obj){
	            if(i == 0){
	                _arr.shift(); //删除并返回数组的第一个元素
	                return;
	            }else if(i == length-1){
	                _arr.pop();  //删除并返回数组的最后一个元素
	                return;
	            }else{
	                _arr.splice(i,1); //删除下标为i的元素
	                return;
	            }
	        }
	    }
	}

	//图片数组
	var fileArr=new Array();
	
	//判断上传照片数量
 	function checkImgNum(){
		if($(".xClass").length+$(".fileClass").length>=8){
			mui.toast("最多上传8张图片");
			$("#morFile").hide();
     		$("#disFile").show();
		}else{
			$("#morFile").show();
     		$("#disFile").hide();
		}
	} 
	
	//上传图片chang事件
	$(".up").change(function () {
        let fileObj = $(this)[0].files;
        let windowURL = window.URL || window.webkitURL;
        let _box = document.getElementById("imgBox")
        let _button = document.getElementById("morFile")
		for(let item of fileObj) {
			if (fileObj.length < (9-$(".xClass").length-$(".fileClass").length)) {
				//图片方向
                var orientation; 
	        	EXIF.getData(item, function(){
	            	orientation = EXIF.getTag(this, 'Orientation');
	            	
	            	let _div = document.createElement("div")
	                _div.style.position = "relative"
	                _div.style.float = "left"
	                let _span = document.createElement("span")
	                _span.style.position = "absolute"
	                _span.style.right = 0
	                _span.style.top = 0
	                _span.style.width = "20px"
	                _span.style.height = "20px"
	                _span.style.zIndex = 1
	                _span.style.display = "block"
	                _span.innerHTML = "x"
	                _span.style.lineHeight = "17px"
	                _span.style.backgroundColor = "#000"
	                _span.style.color = "#fff"
	                _span.style.textAlign = "center"
	                _span.style.borderRadius = "10px"
	                let _img = document.createElement("img")
	                
	                //压缩图片
	                var fileReader = new FileReader();
	            	fileReader.onload = function(){
	            	    var IMG = new Image();
	            		IMG.src = this.result;
	            		IMG.onload = function(){
	            	    	var w = this.naturalWidth, h = this.naturalHeight, resizeW = 0, resizeH = 0;
	            	        // maxSize 是压缩的设置,设置图片的最大宽度和最大高度,等比缩放,level是报错的质量,数值越小质量越低
	            	        var maxSize = {
	            	        	width: 1000,
	            	        	height: 1000,
	            	        	level: 0.7
	            	      	};
	            	      	if(w > maxSize.width || h > maxSize.height){
	            	        	var multiple = Math.max(w / maxSize.width, h / maxSize.height);
	            	        	resizeW = w / multiple;
	            	        	resizeH = h / multiple;
	            	        	
		            	      	var canvas = document.createElement('canvas'),
		            	      	ctx = canvas.getContext('2d');
		            	      	canvas.width = resizeW;
	            	        	canvas.height = resizeH;
	            	        	ctx.drawImage(IMG, 0, 0, resizeW, resizeH);
		            	      	var base64 = canvas.toDataURL('image/jpeg', maxSize.level);
		            	      	_span.classList.add("xClass")
								_span.setAttribute("base64info",base64)//设置属性存储图片base64信息
								_span.setAttribute("orientation_blob",orientation)//设置属性存储图片方向信息(需要压缩的)
	            	      	}else {
	        	            	//选择的图片存到数组中
	        	            	fileArr.push(item);
	        	 	            _div.classList.add("fileClass")
	        	            	_div.setAttribute("orientation_file",orientation)//设置属性存储图片方向信息(无需压缩的)
	            	      	}
	            	      	
	            	     	if($(".xClass").length+$(".fileClass").length>=8){
        	            		$("#morFile").hide();
        	            		$("#disFile").show();
        	            	}
	            	    }
	            	};
	            	fileReader.readAsDataURL(item); 
	            	
	            	_img.classList.add("changImg")
	                _span.addEventListener("click", function(){
						//删除图片时 同时把数组中的相应图片删除
		            	removeArrObj(fileArr,item);
		            	$("#morFile").show();
	                	$("#disFile").hide();
	                	_box.removeChild(_div)
	                })
	                
	                _div.appendChild(_img)
	                _div.appendChild(_span)
	                let dataURL = windowURL.createObjectURL(item);
	                _img.setAttribute('src', dataURL);
	                _box.insertBefore(_div, _button) 
	        	});
            }else{
            	mui.toast("最多上传8张图片");
            }
        }
    })
	
	//将base64转换为blob
	function convertBlob(base64){
		var buffer = new ArrayBuffer(base64.length);
		var ubuffer = new Uint8Array(buffer);
		for (var i = 0; i < base64.length; i++) {
		  ubuffer[i] = base64.charCodeAt(i)
		}
		var blob;
		try {
		    blob = new Blob([buffer], {type: 'image/jpg'});
		} catch (e) {
			window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
		    if(e.name === 'TypeError' && window.BlobBuilder){
		    	var blobBuilder = new BlobBuilder();
		        blobBuilder.append(buffer);
		        blob = blobBuilder.getBlob('image/jpg');
		    }
		}
		return blob;
	}
    
    //提交方法
    function submitFeedback(){
    	//提交按钮禁用
    	$("#subBtn").attr("disabled","disabled");
    	//图片方向字符串
    	var orientationStr="";
    	//先存需要压缩的
    	$(".xClass").each(function(index,item){
    		var orientation_blob=item.getAttribute("orientation_blob");
    		if(orientation_blob==null || orientation_blob=="" || typeof(orientation_blob)=="undefined" || orientation_blob=="undefined"){
    			orientation_blob=1;
    		}
    		orientationStr+=orientation_blob+',';
    	})
    	//再存不需要压缩的
    	$(".fileClass").each(function(index,item){
    		var orientation_file=item.getAttribute("orientation_file");
    		if(orientation_file==null || orientation_file=="" || typeof(orientation_file)=="undefined" || orientation_file=="undefined"){
    			orientation_file=1;
    		}
    		orientationStr+=orientation_file+',';
    	})
    	if(orientationStr.length>0){
    		orientationStr=orientationStr.substring(0,orientationStr.length-1);
    		$("#orientationStr").val(orientationStr);
    	}
    	
    	var formData = new FormData($("#feedbackForm")[0]);//用form表单直接构造formData对象;此时formData中只包含文字信息
    	
    	//先存需要压缩的即blob格式的
    	$(".xClass").each(function(index,item){
    		var base64=item.getAttribute("base64info");
    		if(base64!=null && base64!=""){
    			var blob=convertBlob(window.atob(base64.split(',')[1]));
        		formData.append("file",blob);
    		}
    	})
    	
    	//再存不需要压缩的即file格式的
    	//将数组中的图片存到formData中
    	for(var i=0;i<fileArr.length;i++){
    		formData.append("file",fileArr[i]);//此时formData中既包含文字信息又包含图片信息
    	}
    	
    	//ajax提交表单
      	$.ajax({ 
            async: false,//要求同步
            url : basepath + '/fileAction/fileUpload.do',  
            type : 'POST',  
            data : formData,  
            processData : false,  //必须false才会避开jQuery对formdata的默认处理   
            contentType : false,  //必须false才会自动加上正确的Content-Type 
            success : function(result){
				//success
            }
        }); 
    }
</script>

<!-- <script src="//cdn.jsdelivr.net/npm/eruda"></script>
<script>
	//打开手机调试
    eruda.init();
</script> -->
</body>
</html>
package com.xypt.action.mobile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.xypt.entity.creditFeedback.CreditFeedback;
import com.xypt.utils.ImageHelper;
import com.xypt.utils.PropUtils;
import com.xypt.utils.StringUtil;

/**
 * 投诉或激励
 * 
 * @author SKY 2018年5月23日
 * @description
 *
 */
@RequestMapping("/fileAction")
@Controller
public class FileAction {
	@RequestMapping("/fileUpload")
	public void addCreditFeedbackInfo(@RequestParam(value = "file", required = false)MultipartFile[] file,CreditFeedback creditFeedback,String orientationStr,HttpServletRequest request, HttpServletResponse response) throws IOException {
		String orientationArr[]=orientationStr.split(",");
		List<Integer> orientationList=new ArrayList<Integer>();
		for(String ori:orientationArr){
			if(null!=ori && !"".equals(ori)){
				orientationList.add(Integer.parseInt(ori));
			}
		}
		
		for(int i=0;i<orientationList.size();i++){
			MultipartFile multipartFile=file[i];
			//获取文件名
			String fileName = multipartFile.getOriginalFilename();
			if(null!=fileName && !"".equals(fileName)){
				try {
					String fileExt="";
					if(fileName.equals("blob")){
						String fileType=multipartFile.getContentType();
						System.out.println(fileType);//image/jpg
						fileExt = fileType.substring(fileType.lastIndexOf("/") + 1).toLowerCase();//文件扩展名
					}else{
						fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();//文件扩展名
					}
					
					String newfilename = StringUtil.getUUID() + "." + fileExt; //生成uuid文件名
					String savePath = "upload/images/tsjl/" + newfilename;
					File folder=new File(PropUtils.get("web.root")+"upload/images/tsjl");
					if(!folder.exists()){
						folder.mkdirs();//如果文件夹不存在 创建文件夹
					}
					//旋转图片方向后上传
					ImageHelper.rotateAndUpload(multipartFile.getInputStream(), new File(PropUtils.get("web.root") + savePath), orientationList.get(i));
					
					//数据库保存图片路径信息
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
package com.xypt.utils;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class ImageHelper {
	/**
	 * 实现图像的等比缩放
	 * 
	 * @param source
	 * @param targetW
	 * @param targetH
	 * @return
	 */
	private static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
		// targetW,targetH分别表示目标长和宽
		int type = source.getType();
		BufferedImage target = null;
		double sx = (double) targetW / source.getWidth();
		double sy = (double) targetH / source.getHeight();
		// 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
		// 则将下面的if else语句注释即可
		if (sx < sy) {
			sx = sy;
			targetW = (int) (sx * source.getWidth());
		} else {
			sy = sx;
			targetH = (int) (sy * source.getHeight());
		}
		if (type == BufferedImage.TYPE_CUSTOM) { // handmade
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else
			target = new BufferedImage(targetW, targetH, type);
		Graphics2D g = target.createGraphics();
		// smoother than exlax:
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
		g.dispose();
		return target;
	}

	/**
	 * 实现缩放后的截图
	 * 
	 * @param image
	 *            缩放后的图像
	 * @param subImageBounds
	 *            要截取的子图的范围
	 * @param subImageFile
	 *            要保存的文件
	 * @throws IOException
	 */
	private static void saveSubImage(BufferedImage image, Rectangle subImageBounds, File subImageFile) throws IOException {
		if (subImageBounds.x < 0 || subImageBounds.y < 0 || subImageBounds.width - subImageBounds.x > image.getWidth() || subImageBounds.height - subImageBounds.y > image.getHeight()) {
			// LoggerUtil.error(ImageHelper.class, "Bad subimage bounds");
			return;
		}
		BufferedImage subImage = image.getSubimage(subImageBounds.x, subImageBounds.y, subImageBounds.width, subImageBounds.height);
		String fileName = subImageFile.getName();
		String formatName = fileName.substring(fileName.lastIndexOf('.') + 1);
		ImageIO.write(subImage, formatName, subImageFile);
	}
	
	/**
	 * <p>Title: Rotate</p>  
	 * <p>Description: 图片旋转方法</p>  
	 * @param src 图片
	 * @param angel 旋转角度
	 * @return
	 */
    public static BufferedImage Rotate(Image src, int angel) {  
        int src_width = src.getWidth(null);  
        int src_height = src.getHeight(null);  
        Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);  
  
        BufferedImage res = null;  
        res = new BufferedImage(rect_des.width, rect_des.height,BufferedImage.TYPE_INT_RGB);  
        Graphics2D g2 = res.createGraphics();  
        g2.translate((rect_des.width - src_width) / 2,(rect_des.height - src_height) / 2);  
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);  
  
        g2.drawImage(src, null, null);  
        return res;  
    }  
  
    public static Rectangle CalcRotatedSize(Rectangle src, int angel) {  
        if (angel >= 90) {  
            if(angel / 90 % 2 == 1){  
                int temp = src.height;  
                src.height = src.width;  
                src.width = temp;  
            }  
            angel = angel % 90;  
        }  
  
        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;  
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;  
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;  
        double angel_dalta_width = Math.atan((double) src.height / src.width);  
        double angel_dalta_height = Math.atan((double) src.width / src.height);  
  
        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha  
                - angel_dalta_width));  
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha  
                - angel_dalta_height));  
        int des_width = src.width + len_dalta_width * 2;  
        int des_height = src.height + len_dalta_height * 2;  
        return new Rectangle(new Dimension(des_width, des_height));  
    }  

   /**
	 * <p>Title: rotateAndUpload</p>  
	 * <p>Description: 旋转图片方向并上传</p>  
	 * @param in 输入流
	 * @param saveFile 要保存的图片
	 * @param orientation 图片方向
	 * @return
	 */
	public static boolean rotateAndUpload(InputStream in, File saveFile, int orientation) {
		if (null == in || null == saveFile) {//检查参数有效性
			return false;
		}

		//原始图片
		BufferedImage srcImage = null;
		//旋转后的图片
		BufferedImage rotateImg=null;
	
		try {
			srcImage = ImageIO.read(in);
			
			int angle=0;//角度
		    if(6 == orientation ){
		    	//6旋转90
	            angle = 90;
	        }else if( 3 == orientation){
	        	//3旋转180
	            angle = 180;
	        }else if( 8 == orientation){
	            //8旋转90
	            angle = 270;
	        }else{
	        	angle = 0;
	        }
		    //旋转图片方向
	        rotateImg = Rotate(srcImage, angle);  
	        String fileName = saveFile.getName();//文件名
			String formatName = fileName.substring(fileName.lastIndexOf('.') + 1);//类型
			try {
				ImageIO.write(rotateImg, formatName, saveFile);
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
    
	public static void main(String[] args) throws Exception {
		 File file = new File("f:/111.jpg");
	        
		 int orientation=6;
	     int angle=0;
	     if(6 == orientation ){
	    	 //6旋转90
             angle = 90;
         }else if( 3 == orientation){
             //3旋转180
             angle = 180;
         }else if( 8 == orientation){
             //8旋转90
             angle = 270;
         }
            
         BufferedImage src = ImageIO.read(file);  
         BufferedImage des = Rotate(src, angle);  
         ImageIO.write(des,"jpg", new File("f:/img/test.jpg"));
	}
}


记录一下,欢迎指正
2019-01-25 10:07:21 Chief_fly 阅读数 276

js关键代码片段:

   /*点击头像触发*/ 
             document.getElementById('headImage').addEventListener('tap', function() { 
                    if (mui.os.plus) { 
                        var a = [{ 
                            title: "拍照" 
                        }, { 
                            title: "从手机相册选择" 
                        }]; 
                        plus.nativeUI.actionSheet({ 
                            title: "修改用户头像", 
                            cancel: "取消", 
                            buttons: a 
                        }, function(b) { /*actionSheet 按钮点击事件*/ 
                            switch (b.index) { 
                                case 0: 
                                    break; 
                                case 1: 
                                    getImage(); /*拍照*/ 
                                    break; 
                                case 2: 
                                    galleryImg();/*打开相册*/ 
                                    break; 
                                default: 
                                    break; 
                            } 
                        }) 
                    } 
                }, false); 



    //拍照 
            function getImage() { 
                var c = plus.camera.getCamera(); 
                c.captureImage(function(e) { 
                    plus.io.resolveLocalFileSystemURL(e, function(entry) { 
                        var s = entry.toLocalURL() + "?version=" + new Date().getTime(); 
                        uploadHead(s); /*上传图片*/ 
                    }, function(e) { 
                        console.log("读取拍照文件错误:" + e.message); 
                    }); 
                }, function(s) { 
                    console.log("error" + s); 
                }, { 
                    filename: "_doc/head.png" 
                }) 
            } 




    //本地相册选择 
            function galleryImg() { 
                plus.gallery.pick(function(a) { 
                    plus.io.resolveLocalFileSystemURL(a, function(entry) { 
                        plus.io.resolveLocalFileSystemURL("_doc/", function(root) { 
                            root.getFile("head.png", {}, function(file) { 
                                //文件已存在 
                                file.remove(function() { 
                                    console.log("file remove success"); 
                                    entry.copyTo(root, 'head.png', function(e) { 
                                            var e = e.fullPath + "?version=" + new Date().getTime(); 
                                            uploadHead(e); /*上传图片*/ 
                                            //变更大图预览的src 
                                            //目前仅有一张图片,暂时如此处理,后续需要通过标准组件实现 
                                        }, 
                                        function(e) { 
                                            console.log('copy image fail:' + e.message); 
                                        }); 
                                }, function() { 
                                    console.log("delete image fail:" + e.message); 
                                }); 
                            }, function() { 
                                //文件不存在 
                                entry.copyTo(root, 'head.png', function(e) { 
                                        var path = e.fullPath + "?version=" + new Date().getTime(); 
                                        uploadHead(path); /*上传图片*/ 
                                    }, 
                                    function(e) { 
                                        console.log('copy image fail:' + e.message); 
                                    }); 
                            }); 
                        }, function(e) { 
                            console.log("get _www folder fail"); 
                        }) 
                    }, function(e) { 
                        console.log("读取拍照文件错误:" + e.message); 
                    }); 
                }, function(a) {}, { 
                    filter: "image" 
                }) 
            }; 




    //上传头像图片 
            function uploadHead(imgPath) { 
            	var mainImage = document.getElementById("headImage");
                console.log("imgPath = " + imgPath); 
                mainImage.src = imgPath; 
                mainImage.style.width = "90px"; 
                mainImage.style.height = "90px"; 
     
                var image = new Image(); 
                image.src = imgPath; 
                image.onload = function() { 
              var imgData = getBase64Image(image); 
                    /*在这里调用上传接口*/ 
             var userId=plus.storage.getItem('userId');
			mui.ajax(httpUrl+'appPath/appPath!ajaxUploadImg?userId='+userId,{
				data:{imgData:imgData},
				dataType:'json',//服务器返回json格式数据
				type:'post',//HTTP请求类型
				timeout:10000,//超时时间设置为10秒;
				success:function(data){
					console.log('上传成功'); 
				},
				error:function(xhr,type,errorThrown){
					mui.toast('网络异常,请稍后再试!'); 
				}
			});
                } 
        } 
            //将图片压缩转成base64 
            function getBase64Image(img) { 
                var canvas = document.createElement("canvas"); 
                var width = img.width; 
                var height = img.height; 
                // calculate the width and height, constraining the proportions 
                if (width > height) { 
                    if (width > 100) { 
                        height = Math.round(height *= 100 / width); 
                        width = 100; 
                    } 
                } else { 
                    if (height > 100) { 
                        width = Math.round(width *= 100 / height); 
                        height = 100; 
                    } 
                } 
                canvas.width = width;   /*设置新的图片的宽度*/ 
                canvas.height = height; /*设置新的图片的长度*/ 
                var ctx = canvas.getContext("2d"); 
                ctx.drawImage(img, 0, 0, width, height); /*绘图*/ 
                var dataURL = canvas.toDataURL("image/png", 0.8); 
                return dataURL.replace("data:image/png;base64,", ""); 
            }    

		function photoerror(img){
			img.src="img/mryh.png";
			img.null;   //控制不要一直跳动
		}
2018-09-07 18:02:10 qq_34065701 阅读数 498

依赖:

exif.js,读取图片方向,具体下载地址: [exif.js下载](https://pan.baidu.com/s/1B4LTu0VNwEi_dHF5GibD2g)

代码


       //存储最终文件处理后的base64
    var fileLoad1 = {
        "FileCode": ""
    };
    //文件最大体积
    var imageScale = 1000;

    //input选择文件onchange方法
    function previewImage1(file) {
        if (file.files.length) {
            $('#img2x').empty();//因为一次只能显示一张图,重新选择,清空图片队列
            readImg(file.files[0]);
        }
    }


    //读取图片的横向状态
    function getOrientationOfImage(img) {
        var orient;
        EXIF.getData(img, function () {
            orient = EXIF.getMyTag(this, 'Orientation');
        });
        return orient;
    }


    //判断文件大小并计算新文件宽高
    function readImg(file) {
        var fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = function (e) {
            var image = new Image();
            image.src = e.target['result'];
            image.onload = function (e) {
                var width = image.width;
                var height = image.height;
                if (image.width > imageScale && image.width > image.height) {
                    width = imageScale;
                    height = (imageScale * image.height) / image.width
                }
                else if (image.width > imageScale && image.width < image.height) {
                    height = imageScale;
                    width = (imageScale * image.width) / image.height;
                }
                else if (image.width > imageScale && image.width === image.height) {
                    height = imageScale;
                    width = imageScale;
                }
                //执行压缩旋转
                drawImageAndToBlob(image, 0, 0, width, height);
            };
        }
    }

    //判断图片方向并旋转
    function drawImageAndToBlob(image, x, y, width, height) {
        var canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext('2d');
        var ore = getOrientationOfImage(image);
        if (ore && ore === 6) {
            ctx.save(); //保存状态
            ctx.translate(width / 2, height / 2); //设置画布上的(0,0)位置,也就是旋转的中心点
            ctx.rotate(90 * Math.PI / 180); //把画布旋转90度
// 执行Canvas的drawImage语句
            ctx.drawImage(image, Number(y) - height / 2, Number(x) - width / 2, height, width); //把图片绘制在画布translate之前的中心点,
            ctx.restore(); //恢复状态
        }
        else {
            ctx.drawImage(image, x, y, width, height);
        }
        //canvas获取最终图片文件base64url
        //也可以通过canvas.toBob()方法获取二进制文件,用于直接上传,具体看后台api需要哪种
        var dataUrl = canvas.toDataURL('image/png', 0.9);
        fileLoad1.FileCode = dataUrl;
    }
2016-03-08 17:38:44 z21102 阅读数 3671

这篇文章接着上一篇文章来说。由于公司是做摄影这块的,所以很多开发都涉及到图片的上传。我选择的是与jquery有很好兼容的uploadifive上传插件。

应用插件的时候需要引用这些文件

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="jquery.uploadifive.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="uploadifive.css">
jquery是必须的,因为uploadifive依靠jquery,没有他就无法运行。下面的样式表可以为上传按钮添加上css3的效果。然后需要添加一个input标签来用来做上传的表单按钮
<input id="file_upload" type="file" name="file_upload" />
当然还有我们的js代码。这是官方给出的例子:

$(function() {
    $('#file_upload').uploadifive({
        'uploadScript' : 'uploadifive.php'
        // Put your options here
    });
});
接下来给出的是官方完整的代码

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>UploadiFive</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="jquery.uploadifive-v1.0.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="uploadifive.css">
</head>

<body>
	<h1>UploadiFive Demo</h1>
	<form>
		<input id="file_upload" name="file_upload" type="file" multiple="true">
	</form>

	<script type="text/javascript">
		<?php $timestamp = time();?>
		$(function() {
			$('#file_upload').uploadifive({
				'formData'     : {
					'timestamp' : '<?php echo $timestamp;?>',
					'token'     : '<?php echo md5('unique_salt' . $timestamp);?>'
				},
				'uploadScript' : 'uploadifive.php'
			});
		});
	</script>
</body>
</html>

如果你用的后台是php,可以将
<?php $timestamp = time();?>
放到后台文件中,$timestap是一个时间戳用来记录上传时间。uploadscript引用的文件是uploadifive.php这个是uploadifive的核心。插件支持多图上传和拖拽上传,并且有进度条可以显示上传进度。我用到的是最基本的内容。有兴趣的同学可以登录他的官网进行查阅。地址是http://www.uploadify.com/documentation/uploadifive/implementing-uploadifive/

下面是我在项目中的代码

jQuery('#file_upload').uploadifive({
	'auto'             : true,
	'formData'         : {
						   'timestamp' : '{echo $timestamp;}',
						   'token'     : '{echo md5('unique_salt' . $timestamp);}',
	                     },
	'queueID'			: 'queue',
	'uploadScript'     	: './source/blog/uploadifive/uploadifive.php',
	'removeCompleted' 	: true,
	'buttonText'      	: '',
	'height'            : 32,
	'width'        		: 32,
	'onError'      : function(errorType) {
	            alert('The error was: ' + errorType);
	        },
	'onUpload': function(filesToUpload) {
	        var settings = jQuery(this).data('uploadifive').settings;
	        settings.formData.id = jQuery('.pid').val();
	        jQuery(this).data('uploadifive').settings = settings;
	    },
	'onUploadComplete':function(file,data){
		var data=jQuery.parseJSON(data);
		var delWidth = jQuery(window).width();
		var html = '';
			html += '<li class="bar" data-id="'+data.picid+'" style="position:relative;">';
			html +=	'<div class="leftside" style="width: 875px;">';
			html +=	'<a href="http://bbs.photofans.cn/blog.php?mod=edit_mob&picid='+data.picid+'" data-ajax="false">';
			html +=	'<img class="toolbar" src="'+data.showPath+'" alt="" style="height:50px;width:50px;margin-left:10px;float:left;"/>';
			html += '</a>';
			html += '<input type="hidden" name="picid" class="picid" value="'+data.picid+'"/>';
			html += '<div id="infor" style="font-size:12px;float:left;margin-left:10px;height:50px;width:20%;white-space:pre-wrap;">';
			html += '<div class="infor_up" style="position:absolute;top:0px;height:15px;overflow:hidden;"></div>';
			html +=	'<div class="infor_down" style="position:absolute;bottom:0px;height:15px;overflow:hidden;"></div>';
			html +=	'</div>';
			html +=	'</div>';
			html +=	'<div class="button_scroll">';
			html +=	'<a href="http://bbs.photofans.cn/blog.php?mod=edit_mob&picid='+data.picid+'" class="edit_bar" data-ajax="false"><span class="icon iconfont"></span></a>';
			html +=	'<span class="del_bar icon iconfont"></span>';
			html += '<span class="toolbar" style="line-height:54.9px;height:24px;width:30px;display:block;background:url(./template/default/blog/images/zhuadian.png) no-repeat scroll center center;background-size:20px 20px;padding-top:54px;position:absolute;top:0px;left:116px;"></span>';
			html +=	'</div>';
			html +=	'</li>';

		jQuery('ul[data-role=listview]').append(html);
		jQuery("#kuang").listview('refresh');

	},
	'onQueueComplete' : function(uploads) {
		var sorts = '';
			jQuery('#kuang li').each(function(index, el) {
				sorts += ','+jQuery(this).attr('data-id');
			});
		var id = jQuery('.pid').val();
		jQuery.ajax({
			url: './source/blog/ajax.php',
			type: 'POST',
			dataType: 'json',
			data: {picsorts: sorts,id:id},
			success:function(data){

			}
		})
									           
    }
	
});
里面涉及到一些配置项,auto如果定义成true是自动上传,就是不会经过你点击上传按钮再上传,而是选择完图片就上传成功了。如果你要做一些验证判断或是需要在中途取消一些上传的图片,可以设置成false。默认的情况就是false,所以不建议改。formdate可以用来向后台传递参数,如果你有需要传到后台的数据,可以通过这里设置键值对的方式传到后台,用$_POST获得。queueID是设置作为上传队列的区域的id。removecomplete是上传之后清空队列。buttontext是上传按钮上的文字。height和width是上传选择按钮的宽高。onerror方法是当上传出错的时候执行的。onupload在上传中执行的方法。这里我用来传递pid这个参数。onuploadcomplete是上传完执行的方法。这里我将上传完的数据传回前台,用字符串的方式拼起来,再append到dom结构中,这样可以无刷新的浏览新上传的图片了。onqueuecomplete是整个上传完成之后要做的。

后台代码比较简单:

// 允许类型
$fileTypes = array('jpg', 'jpeg', 'png'); // Allowed file extensions

$verifyToken = md5('unique_salt' . $_POST['timestamp']);

if (!empty($_FILES) && $_POST['token'] == $verifyToken) {

	// 按年/月/目录
	$UploadPath = $uploadDir;
	$upfolder = date("Y")."/".date("m").'/';
	$upfolder_s = date("Y")."/".date("m").'_s/';
	$picpath = $UploadPath.$upfolder;
	$picpath_s = $UploadPath.$upfolder_s;
	// echo $picpath;die;

	// 拼文件名
	$now=time();
	$imgchar=rand(1000,9999);

	// Validate the filetype
	$fileParts = pathinfo($_FILES['Filedata']['name']);
	$extence=strtolower($fileParts['extension']);
	
	$tempFile   = $_FILES['Filedata']['tmp_name'];
	// var_dump($tempFile);die;
	/*=========================================================*/
	$image = imagecreatefromstring(file_get_contents($tempFile));
	$exif = exif_read_data($tempFile);
	if(!empty($exif['Orientation'])) {
	 switch($exif['Orientation']) {
	  case 8:
	   $image = imagerotate($image,90,0);
	   break;
	  case 3:
	   $image = imagerotate($image,180,0);
	   break;
	  case 6:
	   $image = imagerotate($image,-90,0);
	   break;
	 }
	}
	
	/*=========================================================*/
	// 物理路径
	$uploadDir  = rtrim($_SERVER['DOCUMENT_ROOT'],'/');
	// echo $uploadDir;
	// 存入数据库地址
	$targetFilePath = $picpath.$now."_".$imgchar.".".$extence;
	$targetFilePath_s = $picpath_s.$now."_".$imgchar.".".$extence;
	// 物理路径图片地址
	$targetFile = $uploadDir.$targetFilePath;
	$targetFile_s = $uploadDir.$targetFilePath_s;
	// 创建文件夹
	is_dir(dirname($targetFile)) || mkdir(dirname($targetFile),0777,true);
	is_dir(dirname($targetFile_s)) || mkdir(dirname($targetFile_s),0777,true);

	//if ($image) {
	if (in_array(strtolower($fileParts['extension']), $fileTypes)) {

		// Save the file
		// move_uploaded_file($tempFile, $targetFile);
		if ($image !== false) {
			if ($extence === 'png') {
				header('Content-Type: image/png');
				imagepng($image,$targetFile);
				imagedestroy($image);
			}else{
				header('Content-Type: image/jpeg');
				imagejpeg($image,$targetFile);
				imagedestroy($image);
			}
		}
		$data = getimagesize($targetFile);
		//如果上传图片的宽度或高度大于1000px则用命令行缩小到最大尺寸1000================
		if ($data[0]>1000 || $data[1]>1000) {
			$srcFile = $targetFile;
			$dstFile = $targetFile;
			$dstW_s = "1000";
			$dstH_s = "1000";
			$exec_str = "/usr/local/bin/convert -geometry ".$dstW_s."x".$dstH_s." ".$srcFile." ".$dstFile;
			@exec($exec_str);
		}
		/*================================================================================*/
		// 裁切300*300的小图
		$srcFile_s = $targetFile;
		$dstFile_s = $targetFile_s;
		$dstW = "800";
		$dstH = "800";
		$exec_str = "/usr/local/bin/convert -geometry ".$dstW."x".$dstH." ".$srcFile_s." ".$dstFile_s;
		@exec($exec_str);
		$dstWnew = "300";
		$dstHnew = "300";
		$data_s = getimagesize($targetFile_s);
		$dstWx = ($data_s[0]/2)-150;
		$dstHy = ($data_s[1]/2)-150;
		$exec_str_cut = "/usr/local/bin/convert -crop ".$dstWnew."x".$dstHnew."+".$dstWx."+".$dstHy." ".$dstFile_s." ".$dstFile_s;
		@exec($exec_str_cut);
		/*================================================================================*/
		$pic = 'uploads'.$upfolder;
		$pic = rtrim($pic,'/');
		$image = $now."_".$imgchar.".".$extence;
		$showPath = 'http://www.fansimg.com/'.$pic.'_s/'.$image;
		//插入pic表图片id,imagename,upfolder
		$uid = (int)$_G['uid'];
		$id = $_POST['id'];
		if ($id == '' || $id == null) {
			$id = 0;
		}
		$picid = DB::insert('blog_pics',array('uploader'=>$pic,'imagename'=>$image,'uid'=>$uid,'draftid'=>$id,'dateline'=>time()),1);
		//插入博客表
		$total = array(
			'showPath'=>$showPath,
			'picid'	=>$picid
			);
		echo json_encode($total);die;
	} else {

		// The file type wasn't allowed
		echo 'Invalid file type.';

	}
}

后台代码看着比较多,但是很好理解。就是获得上传图片,将图片上传到设置好的文件夹中,然后可以将所需要的数据查到数据库中。具体的代码我就不讲解了。

好了上传部分结束。

Vue2.0 webApp视频预览并上传,百分比进度显示

阅读数 5443

 &lt;p&gt;请选择或者拍摄视频上传&lt;/p&gt; &lt;inputtype="file"accept="video/avi,video/mp4,video/flv,video/3gp,video/swf"capture="camcorder"@change="onFileChange"style="display:none;"&g

博文 来自: qq_27717857

更改Eclipse下Tomcat的部署目录 ,防止上传的文件是到eclipse的克隆的tomcat上的webapp,而不是tomcat本身的webapp

阅读数 1387

使用eclipse开发是因为机器不够用myeclipse,eclipse也比myeclipse清爽很多,启动速度也快。这里的搭建开发环境使用:Jdk1.6+Tomcat6+EclipseJEE,工作目录如下环境目录如下:      安装路径:      C:\Java\Jdk1.6.0      C:\Java\Jre1.6.0      D:\Tomca

博文 来自: yang3866910

更改Eclipse下Tomcat的部署目录 ,防止上传的文件是到eclipse的克隆的tomcat上的webapp,而不是tomcat本身的webapp

阅读数 223

使用eclipse开发是因为机器不够用myeclipse,eclipse也比myeclipse清爽很多,启动速度也快。这里的搭建开发环境使用:Jdk1.6+Tomcat6+EclipseJEE,工作目录如下环境目录如下:      安装路径:      C:\Java\Jdk1.6.0      C:\Java\Jre1.6.0      D:\Tomcat6.0

博文 来自: u011530389

更改Eclipse下Tomcat的部署目录 ,防止上传的文件是到eclipse的克隆的tomcat上的webapp,而不是tomcat本身的webapp

阅读数 310

使用eclipse开发是因为机器不够用myeclipse,eclipse也比myeclipse清爽很多,启动速度也快。这里的搭建开发环境使用:Jdk1.6+Tomcat6+EclipseJEE,工作目录如下环境目录如下:      安装路径:      C:\Java\Jdk1.6.0      C:\Java\Jre1.6.0      D:\T

博文 来自: SHANDFOU

更改Eclipse下Tomcat的部署目录 ,防止上传的文件是到eclipse的克隆的tomcat上的webapp,而不是tomcat本身的webapp

阅读数 949

源自:http://www.cnblogs.com/losesea/archive/2013/11/11/3418009.html使用eclipse开发是因为机器不够用myeclipse,eclipse也比myeclipse清爽很多,启动速度也快。这里的搭建开发环境使用:Jdk1.6+Tomcat6+EclipseJEE,工作目录如下环境目录如下:      安

博文 来自: gaoshanliushui2009
没有更多推荐了,返回首页