wenjien

//文件上传
@ResponseBody
@RequestMapping(value = "uploadMp3",method=RequestMethod.POST)
@ActionLog(title="【上传图片】", action="Image/UploadImage")
public ResultModel uploadMp3(HttpServletRequest request, HttpServletResponse response,@RequestParam("file") MultipartFile file1) throws Exception
{
//String url ="111";
System.out.println(file1);

    // 创建一个通用的多部分解析器
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    // 判断 request 是否有文件上传,即多部分请求
    if (multipartResolver.isMultipart(request))
    {
        // 转换成多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        OSSClientUtil oss = new OSSClientUtil();
        String url = null;
        try {
			if(multiRequest.getFileMap().size()==1){
				// 获得文件
			    MultipartFile file = file1;
			    url = oss.uploadImg2Oss(file);
			}else {
				return new ResultModel<String>("不能上传多个图片!", null);
			}
		} 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.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } 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.");
            System.out.println("Error Message: " + ce.getMessage());
        } finally {
        	oss.destory();
        }
        return new ResultModel<String>("上传成功!", url);
    }else{
    	return new ResultModel<String>("没有图片!", null);
    }
    

   
}

}

//////////////////////////////////*******************************************************
package com.function.oss;

import java.io.File;
import java.net.URL;

import org.apache.log4j.Logger;
import java.io.*;
import java.util.Date;
import java.util.Random;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.common.util.DateUtil;
import com.common.util.MyProperitesUtil;

import org.springframework.web.multipart.MultipartFile;
import com.function.exception.BizException;

public class OSSClientUtil {

public static final Logger logger = Logger.getLogger(OSSClientUtil.class);

private static String endpoint = MyProperitesUtil.createInstance().getProperty("OSS_ENDPOINT");
private static String accessKeyId = MyProperitesUtil.createInstance().getProperty("OSS_ACCESSKEYID");
private static String accessKeySecret = MyProperitesUtil.createInstance().getProperty("OSS_ACCESSKEYSECRET");
private static String bucketName = MyProperitesUtil.createInstance().getProperty("OSS_BUCKETNAME");
private static String cdnDomain = MyProperitesUtil.createInstance().getProperty("OSS_CDNDOMAIN");

private static String imgdir = "file/images/review/";
private static String apkdir = "file/version/apk/";

private OSSClient ossClient;

public OSSClientUtil() {
	init();
}

/**
 * 初始化
 */
public void init() {
	ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}

/**
 * 销毁
 */
public void destory() {
	ossClient.shutdown();
}

/**
 * 上传图片
 * 
 * @param url
 * @throws ImgException
 */
public void uploadImg2Oss(String url) throws BizException {
	File fileOnServer = new File(url);
	FileInputStream fin;
	try {
		fin = new FileInputStream(fileOnServer);
		String[] split = url.split("/");
		this.uploadFile2OSS(fin, split[split.length - 1]);
	} catch (FileNotFoundException e) {
		throw new BizException("图片上传失败");
	}
}

public String uploadImg2Oss(MultipartFile file,String name) throws BizException {
	String filenameExtension = name.substring(name.lastIndexOf(".")+1);
	if (filenameExtension.equalsIgnoreCase("apk")) {
		if (file.getSize() > 50 * 1024 * 1024) {
			throw new BizException("上传文件大小不能超过50M!");
		}
	}else {
		if (file.getSize() > 10 * 1024 * 1024) {
			throw new BizException("上传图片大小不能超过10M!");
		}
	}
	
	try {
		
		InputStream inputStream = file.getInputStream();
		this.uploadFile2OSS(inputStream, name);
		return name;
	} catch (Exception e) {
		e.printStackTrace();
		throw new BizException("文件上传失败");
	}
}

public String uploadImg2Oss(MultipartFile file) throws BizException {
	String originalFilename = file.getOriginalFilename();
	String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
	Random random = new Random();
	String name = DateUtil.getDateMillisecond() + random.nextInt(1000) + substring;
	
    this.uploadImg2Oss(file,name);
    String url = this.getUrl(name);
    return url;
}

/**
 * 获得url链接
 * 
 * @param key
 * @return
 */
public String getUrl(String key) {
	// 设置URL过期时间为10年 3600l* 1000*24*365*10
	Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
	// 生成URL
	URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);

// String compress = "?x-oss-process=image/resize,m_mfit,h_500,w_500";
if (url != null) {
String sb = url.toString();
sb = sb.substring(0, sb.indexOf("?"));
sb = sb.substring(0, sb.lastIndexOf("/"));
sb = sb+"/"+getDir(key) +key;
return sb;
}
return cdnDomain+"/"+key;
}

/**
 * 上传到OSS服务器 如果同名文件会覆盖服务器上的
 * 
 * @param instream 文件流
 * @param fileName 文件名称 包括后缀名
 * @param fileType 1图片2APK
 * @return 出错返回"" ,唯一MD5数字签名
 */
public String uploadFile2OSS(InputStream instream, String fileName) {
	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(".")+1)));
		objectMetadata.setContentDisposition("inline;filename=" + fileName);
		BufferedInputStream bufferInputStream = new BufferedInputStream(instream, 1024*1024*10);
		//好像没改对····
		// 上传文件
		
		
		//PutObjectResult putResult = ossClient.putObject(bucketName, getDir(fileName) + fileName, instream, objectMetadata);
		PutObjectResult putResult = ossClient.putObject(bucketName, getDir(fileName) + fileName, bufferInputStream, 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;
}

/**
 * Description: 判断OSS服务文件上传时文件的contentType
 * 
 * @param FilenameExtension
 *            文件后缀
 * @return String
 */
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";
	}
	if (filenameExtension.equalsIgnoreCase("apk")) {
		return "application/vnd.android.package-archive";
	}
	return "image/jpeg";
}

/**
 * 判断文件类型,不同的上传路径
 * @param filenameExtension
 * @return
 */
public static String getDir(String fileName) {
	String filenameExtension = fileName.substring(fileName.lastIndexOf(".")+1);
	if (filenameExtension.equalsIgnoreCase("apk")) {
		return apkdir;
	}else {
		return imgdir;
	}
}

}

上一篇:java获取访问地址IP的简单方法


下一篇:java spring获取请求ip地址