上传图片的页面部分
<div class="goodsS22-file goodsS22-g">
<span class="fl">上传图片</span><div class="layui-form-item fl">
<div class="layui-input-block">
<input id="head" name="head" type="hidden" value=""/>
<img id="head_img" style="width: 130px;height: 130px;" src="${productV1.originalimg}"/>
<a style="left:0;top:0;width:130px;height:130px;" class="upload" href="javascript:clickUpload('photo');">
<span class='upload-button'>上传图片</span>
</a>
<input type="file" style="display: none;" class="fileupload" name="file" id="photo" οnchange="checkImgType('photo','head_img','head','3','1')" />
</div>
</div>
</div>
上传图片的js:
function checkImgType(fileid, imgId, hiddenId, objType, objId) {
var filePath = $("#" + fileid).val().toLowerCase();
var fileType = 'jpg,gif,png,bmp,jpeg,tif';
if (filePath == '') {
layer.msg('请选择文件!');
return;
}
filePath = filePath.substring(filePath.lastIndexOf(".") + 1,filePath.length);
if (fileType.toUpperCase().indexOf(filePath.toUpperCase()) == -1){
layer.msg('该文件类型不允许上传!支持格式' + fileType);
return;
}
ajaxFileUpload(fileid, imgId, hiddenId, objType, objId);
}
function ajaxFileUpload(fileid, imgId, hiddenId, objType, objId) {
$.ajaxFileUpload({
url : WebUtil.constants.WEB_CONTEXTPATH + '/uploadImage',
type: 'post',
secureuri : false,
fileElementId : fileid,
dataType: 'text',
data : {
"objType" : objType,
"objId" : objId
},
success : function(result){
$("#" + imgId).attr("src", escape2Html(result));
$("#" + hiddenId).val(result);
}
});
return false;
}
function clickUpload(id) {
document.getElementById(id).click()
}
function escape2Html(sHtml) {
var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
return sHtml.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
}
引用的jquery-upload.js:
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
if (data){
for (var i in data){
$('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
$(form).appendTo('body');
return form;
},
addOtherRequestsToForm: function(form,data)
{
// add extra parameter
var originalElement = $('<input type="hidden" name="" value="">');
for (var key in data) {
name = key;
value = data[key];
var cloneElement = originalElement.clone();
cloneElement.attr({'name':name,'value':value});
$(cloneElement).appendTo(form);
}
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, s.data);
if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "text" )
{
//duyy 因为返回的json自动包装了<pre>,导致前台无法解析 2017-07-05 18:25:41
data = data.replace("<pre>","").replace("</pre>","");
// If you add mimetype in your response,
// you have to delete the '<pre></pre>' tag.
// The pre tag in Chrome has attribute, so have to use regex to remove
// var data = r.responseText;
// var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
// var am = rx.exec(data);
// //this is the desired data extracted
// var data = (am) ? am[1] : ""; //the only submatch or empty
// eval( "data = " + data );
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
},
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}
})
controller层代码:
@RequestMapping(value = "uploadImage", method = RequestMethod.POST)
@ResponseBody
public String uploadImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
log.debug("文件名称: " + file.getOriginalFilename());
log.debug("文件长度: " + file.getSize());
log.debug("文件类型: " + file.getContentType());
Map<String, Object> returnMap =new HashMap<String, Object>();
String path = "";
if (null!=file && !file.isEmpty()) {
Map<String, Object> paramMap =new HashMap<String, Object>();
paramMap.put("objType", request.getParameter("objType")); //所属模块
paramMap.put("objId", request.getParameter("objId")); //图片名称
// String path = OSSClientUtil.uploadImg2Oss(OSSClientUtil.getOSSClient(), file,paramMap);
//
// String path = OSSClientUtil.uploadImg2Oss(OSSClientUtil.getOSSClient(), file,paramMap);
path = OSSClientUtil.uploadImg2Oss(OSSClientUtil.getOSSClient(), file,paramMap);
System.out.println(path);
returnMap.put("path", path);
}
return path;
}
工具类OSSCLientUtil:
package com.tutu.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
/**
*
* @ClassName: OSSClientUtil
* @Description: 阿里云图片处理
* @author duyy
* @date 2017年8月9日 下午2:57:33
*
*/
public class OSSClientUtil {
常量介绍;
- /**
- * @class:OSSClientConstants
- * @descript:阿里云注册用户基本常量
- * @date:2017年3月16日 下午5:52:34
- * @author sang
- */
- public class OSSClientConstants {
- //阿里云API的外网域名
- public static final String ENDPOINT = "oss-cn-shanghai.aliyuncs.com";
- //阿里云API的密钥Access Key ID
- public static final String ACCESS_KEY_ID = "LTAIRGxaf6yoUsj0";
- //阿里云API的密钥Access Key Secret
- public static final String ACCESS_KEY_SECRET = "3gcfQkeWjaJ3tunuv4yyY4DStgpriz";
- //阿里云API的bucket名称
- public static final String BACKET_NAME = "uploadpicture";
- //阿里云API的文件夹名称
- public static final String FOLDER="somnus/";
private static final Logger logger = Logger.getLogger(OSSClientUtil.class);
private static final String ENDPOINT = "http://oss-cn-shenzhen.aliyuncs.com";
private static final String ACCESS_KEY_ID = "LTAIRuqYQMVuUusG";
private static final String ACCESS_KEY_SECRET = "Q1g7tZgTPTeMbb9HHRrIxf8SBbdbXE";
private static final String BUCKETNAME = "tutuimg1";
private static String FILEDIR = "emll/";
/**
*
* @Title: getOSSClient
* @Description: 获取OSSClient
* @param: @return
* @return: OSSClient
* @throws
*/
public static final OSSClient getOSSClient(){
FILEDIR = "emll/";
return new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
/**
*
* @Title: uploadImg2Oss
* @Description: 上传图片
* @param: @param ossClient
* @param: @param MultipartFile
* @param: @return
* @return: String
* @throws
*/
public static String uploadImg2Oss(OSSClient ossClient, MultipartFile file,Map<String, Object> paramMap) {
if (file.getSize() > 1024 * 1024) {
logger.error("上传图片大小不能超过1M!");
}
String originalFilename = file.getOriginalFilename();
//文件后缀
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
//TODO 重新命名文件名称 http://tutuimg1.oss-cn-shenzhen.aliyuncs.com/emll/1502267932376.png /Goods/20170807/Goods_20170807_商品ID.jpg
Random random = new Random();
String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
//String name = paramMap.get("objId")+"_"+"g1"+substring;
try {
InputStream inputStream = file.getInputStream();
uploadFile2OSS(ossClient, inputStream, name,paramMap);
} catch (Exception e) {
logger.error("图片上传失败");
}
return getImgUrl(ossClient, name);
}
/**
*
* @Title: uploadFile2OSS
* @Description: TODO
* @param: @param ossClient
* @param: @param instream
* @param: @param fileName
* @param: @return
* @return: String
* @throws
*/
public static String uploadFile2OSS(OSSClient ossClient, InputStream instream, String fileName,Map<String, Object> paramMap) {
String ret = "";
try {
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
String time = StringUtils.ymdTime();//公共方法获取时间年月日
String objType=paramMap.get("objType")+"";
if(objType.equals(Constants.OBJ_TYPE_1+"")){
FILEDIR+="user/"+time+"/uesr_"+time+"_";
}else if(objType.equals(Constants.OBJ_TYPE_2+"")){
FILEDIR+="businessman/"+time+"/businessman_"+time+"_";
}else if(objType.equals(Constants.OBJ_TYPE_3+"")){
FILEDIR+="googs/"+time+"/googs_"+time+"_";
}else if(objType.equals(Constants.OBJ_TYPE_4+"")){
FILEDIR+="cate/"+time+"/cate_"+time+"_";
}else if(objType.equals("5")){
FILEDIR+="menu/"+time+"/Menu_"+time+"_";
}else{
FILEDIR+="common/"+time+"/Common_"+time+"_"; //xxxx/common/2017817/123123123.png
}
//fileName = FILEDIR.replace("/", "_")+fileName;
// 上传文件
PutObjectResult putResult = ossClient.putObject(BUCKETNAME, FILEDIR + fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
*
* @Title: getImgUrl
* @Description: 获得图片路径
* @param: @param ossClient
* @param: @param fileUrl
* @param: @return
* @return: String
* @throws
*/
public static String getImgUrl(OSSClient ossClient, String fileUrl) {
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return getUrl(ossClient, FILEDIR + split[split.length - 1]);
}
return null;
}
/**
*
* @Title: getUrl
* @Description: 设置URL过期时间为10年
* @param: @param ossClient
* @param: @param key
* @param: @return
* @return: String
* @throws
*/
public static String getUrl(OSSClient ossClient, String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(BUCKETNAME, key, expiration);
if (url != null) {
return url.toString();
}
return null;
}
/**
* 创建存储空间
* @param ossClient
* @param bucketName 存储空间
* @return
*/
public static String createBucket(OSSClient ossClient,String bucketName){
//存储空间
final String bucketNames=bucketName;
if(!ossClient.doesBucketExist(bucketName)){
//创建存储空间
Bucket bucket=ossClient.createBucket(bucketName);
logger.info("创建存储空间成功");
return bucket.getName();
}
return bucketNames;
}
/**
*
* @Title: deleteBucket
* @Description: 删除存储空间buckName
* @param: @param ossClient
* @param: @param bucketName
* @return: void
* @throws
*/
public static void deleteBucket(OSSClient ossClient, String bucketName) {
ossClient.deleteBucket(bucketName);
logger.info("删除" + bucketName + "Bucket成功");
}
/**
*
* @Title: createFolder
* @Description: 创建模拟文件夹
* @param: @param ossClient
* @param: @param bucketName
* @param: @param folder
* @param: @return
* @return: 文件名称
* @throws
*/
public static String createFolder(OSSClient ossClient, String bucketName, String folder) {
// 文件夹名
final String keySuffixWithSlash = folder;
// 判断文件夹是否存在,不存在则创建
if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
// 创建文件夹
ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
// 得到文件夹名
OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
String fileDir = object.getKey();
return fileDir;
}
return keySuffixWithSlash;
}
/**
*
* @Title: getcontentType
* @Description: 判断OSS服务文件上传时文件的contentType
* @param: @param FilenameExtension
* @param: @return
* @return: String
* @throws
*/
public static String getContentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase("bmp")) {
return "image/bmp";
}
if (FilenameExtension.equalsIgnoreCase("gif")) {
return "image/gif";
}
if (FilenameExtension.equalsIgnoreCase("jpeg") || FilenameExtension.equalsIgnoreCase("jpg")
|| FilenameExtension.equalsIgnoreCase("png")) {
return "image/jpeg";
}
if (FilenameExtension.equalsIgnoreCase("html")) {
return "text/html";
}
if (FilenameExtension.equalsIgnoreCase("txt")) {
return "text/plain";
}
if (FilenameExtension.equalsIgnoreCase("vsd")) {
return "application/vnd.visio";
}
if (FilenameExtension.equalsIgnoreCase("pptx") || FilenameExtension.equalsIgnoreCase("ppt")) {
return "application/vnd.ms-powerpoint";
}
if (FilenameExtension.equalsIgnoreCase("docx") || FilenameExtension.equalsIgnoreCase("doc")) {
return "application/msword";
}
if (FilenameExtension.equalsIgnoreCase("xml")) {
return "text/xml";
}
return "image/jpeg";
}
}
阿里云的jar包;
<!-- aliyun-sdk-oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>