java 七牛上传图片到服务器(采用的html5 压缩 传输base64方式)
//html 页面如下
<div class="form-group"> <label class="col-sm-2 control-label">上传头像</label> <div class="col-sm-6"> <input id="appHiddenMain" type="hidden" name="img" value="https://images.gagahi.com/images/default/male.png" /> <input type="file" id="photo" accept="image/*"> <img style="width:160px;" src="https://images.gagahi.com/images/default/male.png" id="imgd1" /> </div> </div> <script type="text/javascript"> $('#photo').change(function () { var _this = $(this)[0], _file = _this.files[0], fileType = _file.type; if (/image\/\w+/.test(fileType)) { //提示 var index = layer.open({ content: '图片上传中...' , skin: 'msg' }); var fileReader = new FileReader(); fileReader.readAsDataURL(_file); fileReader.onload = function (event) { var result = event.target.result; //返回的dataURL var image = new Image(); image.src = result; image.onload = function () { //创建一个image对象,给canvas绘制使用 var cvs = document.createElement('canvas'); var scale = 1; if (this.width > 1000 || this.height > 1000) { //1000只是示例,可以根据具体的要求去设定 if (this.width > this.height) { scale = 1000 / this.width; } else { scale = 1000 / this.height; } } cvs.width = this.width * scale; cvs.height = this.height * scale; //计算等比缩小后图片宽高 var ctx = cvs.getContext('2d'); ctx.drawImage(this, 0, 0, cvs.width, cvs.height); var newImageData = cvs.toDataURL(fileType, 0.8); //重新生成图片,<span style="font-family: Arial, Helvetica, sans-serif;">fileType为用户选择的图片类型</span> var sendData = newImageData.replace("data:" + fileType + ";base64,", ''); $.post('${base}/file/upload/sendImg.do', {imgCode: sendData}, function (data) { if (data != '') { $('.modify_img').attr('src', newImageData); $("#appHiddenMain").val(data); $("#imgd1").attr("src",data); layer.closeAll(); } else { layer.closeAll(); layer.open({ content: '上传失败' , skin: 'msg' }); } }); } } } else { layer.open({ content: '请选择图片格式文件' , skin: 'msg' }); } }); </script>
java代码如下
package com.aaa.qiniu; import java.io.ByteArrayInputStream; import java.io.IOException; import com.qiniu.common.QiniuException; import com.qiniu.common.Zone; import com.qiniu.http.Response; import com.qiniu.storage.Configuration; import com.qiniu.storage.UploadManager; import com.qiniu.util.Auth; import com.aaa.utils.UUIDGenerator; import sun.misc.BASE64Decoder; public class CoverUpload { // 上传到七牛后保存的文件名 //String key = "gagaTest.json"; // 上传文件的路径 //String filePath = "D:\\gagaTest.json"; // 密钥配置 private static Auth auth = Auth.create(QiniuConfig.ACCESS_KEY, QiniuConfig.SECRET_KEY); // 创建上传对象 private static UploadManager uploadManager = new UploadManager(new Configuration(Zone.zone0())); // 覆盖上传 private static String getUpToken(String key) { // <bucket>:<key>,表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”,已存在同名资源则会被本次覆盖。 // 如果希望只能上传指定key的文件,并且不允许修改,那么可以将下面的 insertOnly 属性值设为 1。 // 第三个参数是token的过期时间 return auth.uploadToken(QiniuConfig.bucketname, key/*, 3600, new StringMap().put("insertOnly", 1)*/); } public static boolean upload(String filePath, String key) throws IOException { try { // 调用put方法上传,这里指定的key和上传策略中的key要一致 Response res = uploadManager.put(filePath, key, getUpToken(key)); // 打印返回的信息 System.out.println(res.bodyString()); } catch (QiniuException e) { Response r = e.response; // 请求失败时打印的异常的信息 System.out.println(r.toString()); try { // 响应的文本信息 System.out.println(r.bodyString()); } catch (QiniuException e1) { // ignore } return false; } return true; } //采用的html5 压缩 传输base64方式 public static boolean uploadHtml5(String imgStr,String key) { BASE64Decoder decoder = new BASE64Decoder(); try { //Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {//调整异常数据 b[i] += 256; } } ByteArrayInputStream byteInputStream = new ByteArrayInputStream(b); // 调用put方法上传,这里指定的key和上传策略中的key要一致 Response response = uploadManager.put(byteInputStream, key, getUpToken(key), null, null); // 打印返回的信息 System.out.println(response.bodyString()); } catch (Exception e) { e.printStackTrace(); // 请求失败时打印的异常的信息 System.out.println(imgStr); return false; } return true; } // public static void main(String args[]) throws IOException { // new CoverUpload().upload("C:\\Users\\Administrator\\Desktop\\ip2222222.jpg","tianwenhui111333.jpg"); // } }