上传图片操作小结

图片上传操作是一种很常见的操作,多用于后台管理。应用场景有上传头像、上传封面,上传轮播图等。这篇博客介绍的是单图片上传,多图片上传请看下一篇博客。

本博客将分三个部分来进行代码演示:html代码,JS代码及后台接口代码。

一、HTML代码

下面这段代码运行后页面中会出现上传图片按钮、预览图片等内容。

二、JS代码

//普通图片上传
  var uploadInst = upload.render({
    elem: '#test1'
    ,url: '/upload/'
    ,before: function(obj){
      //预读本地文件示例,不支持ie8
      obj.preview(function(index, file, result){
        $('#demo1').attr('src', result); //图片链接(base64)
      });
    }
    ,done: function(res){
      //如果上传失败
      if(res.code > 0){
        return layer.msg('上传失败');
      //上传成功
	  }else{
		return layer.msg('上传成功');
	  }
    }
    ,error: function(){
      //演示失败状态,并实现重传
      var demoText = $('#demoText');
      demoText.html('上传失败 重试');
      demoText.find('.demo-reload').on('click', function(){
        uploadInst.upload();
      });
    }
  });

三、后台接口

OSS提供的接口示例,个人进行了一些调整,回传访问路径、上传耗时等数据供前端处理。(阿里云官方文档链接:https://help.aliyun.com/document_detail/32013.html?spm=a2c4g.11186623.6.729.2d25c06dW7jZ1D)

/**
 * 上传文件Controller
 * @author 梁钟
 * @date 2018-04-20
 */

@Controller
@RequestMapping("/system/upload")
public class UploadFileController {
	
	private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";// 
	private static String accessKeyId = "accessKeyId ";// 
	private static String accessKeySecret = "accessKeySecret ";// 
	private static String bucketName = "bb269e6e-4516-f8be-b132-8019100a4763";// 

	
	/**
	 * 上传图片
	 * @param uploadFile
	 * @return
	 * @throws Exception
	 */
	public static Map QRcodeUpload(InputStream in) throws Exception {
		// 上传
		long startTime = System.currentTimeMillis();// 开始时间
		String key = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/"
				+ UUID.randomUUID().toString();// oss文件名(Object Name)
//				+ UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);// oss文件名(Object Name)
		/*
		 * Constructs a client instance with your account for accessing OSS
		 */
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			// new对象元信息
			ObjectMetadata meta = new ObjectMetadata();
			// 设置contentType
			meta.setContentType("image/jpeg");
			// 上传文件
			ossClient.putObject(bucketName, key, in, meta);
		} catch (OSSException oe) {
			System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
		} catch (ClientException ce) {
			System.out.println("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
		} finally {
			/*
			 * Do not forget to shut down the client finally to release all allocated resources.
			 */
			ossClient.shutdown();
		}
		long endTime = System.currentTimeMillis();// 结束时间
		// 出参
		String baseFilePath = "http://bb269e6e-4516-f8be-b132-8019100a4763.oss-cn-hangzhou.aliyuncs.com/";
		Map respMap = new HashMap();
//		respMap.put("uploadFileName", uploadFile.getOriginalFilename());// 文件名称
		respMap.put("uploadFilePath", baseFilePath + key);// 访问路径
		RespBean> respBean = new RespBean>();
		respBean.setBody(respMap);
		System.err.println("\n上传耗时:" + (endTime - startTime)/1000.0 + "s");
		System.err.println("访问路径:" + respMap.get("uploadFilePath"));
		return respMap;
	}

}

你可能感兴趣的:(上传图片操作小结)