oss图片上传:
1、OSSManageUtil工具类
@SuppressWarnings("restriction")
public class OSSManageUtil {
/**
* 上传OSS服务器文件 @Title: uploadFile
* @param multipartFile spring 上传的文件
* remotePath @param oss服务器二级目录
* @throws Exception 设定文件 @return String
* 返回类型 @throws
*/
@SuppressWarnings("deprecation")
public static String uploadFile(InputStream fileContent, String remotePath,String fileName) throws Exception {
//随机名处理
fileName = "yw_" + new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
// 加载配置文件,初始化OSSClient
OSSConfigure ossConfigure = new OSSConfigure("oss/oss.properties");
OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
ossConfigure.getAccessKeySecret());
// 定义二级目录
String remoteFilePath = remotePath.substring(0, remotePath.length()).replaceAll("\\\\", "/") + "/";
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(fileContent.available());
objectMetadata.setContentEncoding("utf-8");
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(contentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
// 上传文件
ossClient.putObject(ossConfigure.getBucketName(), remoteFilePath + fileName, fileContent, objectMetadata);
// 关闭OSSClient
ossClient.shutdown();
// 关闭io流
fileContent.close();
return ossConfigure.getAccessUrl() + "/" + remoteFilePath + fileName;
}
// 下载文件
@SuppressWarnings({ "unused", "deprecation" })
public static void downloadFile(OSSConfigure ossConfigure, String key, String filename)
throws OSSException, ClientException, IOException {
// 初始化OSSClient
OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
ossConfigure.getAccessKeySecret());
OSSObject object = ossClient.getObject(ossConfigure.getBucketName(), key);
// 获取ObjectMeta
ObjectMetadata meta = object.getObjectMetadata();
// 获取Object的输入流
InputStream objectContent = object.getObjectContent();
ObjectMetadata objectData = ossClient.getObject(new GetObjectRequest(ossConfigure.getBucketName(), key),
new File(filename));
// 关闭数据流
objectContent.close();
}
/**
* 根据key删除OSS服务器上的文件 @Title: deleteFile @Description: @param @param
* ossConfigure @param @param filePath 设定文件 @return void 返回类型 @throws
* @throws IOException
*/
@SuppressWarnings("deprecation")
public static void deleteFile( String filePath) throws IOException {
// 加载配置文件,初始化OSSClient
OSSConfigure ossConfigure = new OSSConfigure("/oss.properties");
OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
ossConfigure.getAccessKeySecret());
ossClient.deleteObject(getOSSBucketName(filePath), getOSSFileName(filePath));
}
/**
* Description: 判断OSS服务文件上传时文件的contentType @Version1.0
*
* @param FilenameExtension
* 文件后缀
* @return String
*/
public static String contentType(String FilenameExtension) {
if (FilenameExtension.equals(".BMP") || FilenameExtension.equals(".bmp")) {
return "image/bmp";
}
if (FilenameExtension.equals(".GIF") || FilenameExtension.equals(".gif")) {
return "image/gif";
}
if (FilenameExtension.equals(".JPEG") || FilenameExtension.equals(".jpeg") || FilenameExtension.equals(".JPG")
|| FilenameExtension.equals(".jpg") || FilenameExtension.equals(".PNG")
|| FilenameExtension.equals(".png")) {
return "image/jpeg";
}
if (FilenameExtension.equals(".HTML") || FilenameExtension.equals(".html")) {
return "text/html";
}
if (FilenameExtension.equals(".TXT") || FilenameExtension.equals(".txt")) {
return "text/plain";
}
if (FilenameExtension.equals(".VSD") || FilenameExtension.equals(".vsd")) {
return "application/vnd.visio";
}
if (FilenameExtension.equals(".PPTX") || FilenameExtension.equals(".pptx") || FilenameExtension.equals(".PPT")
|| FilenameExtension.equals(".ppt")) {
return "application/vnd.ms-powerpoint";
}
if (FilenameExtension.equals(".DOCX") || FilenameExtension.equals(".docx") || FilenameExtension.equals(".DOC")
|| FilenameExtension.equals(".doc")) {
return "application/msword";
}
if (FilenameExtension.equals(".XML") || FilenameExtension.equals(".xml")) {
return "text/xml";
}
if (FilenameExtension.equals(".apk") || FilenameExtension.equals(".APK")) {
return "application/octet-stream";
}
return "text/html";
}
@SuppressWarnings("unused")
public static void main(String[] args) {
try {
OSSConfigure ossConfigure = new OSSConfigure("oss.properties");
//deleteFile("http://ceshi1111111.oss-cn-hangzhou.aliyuncs.com/cardImage/yw_1524552090254.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @MethodName: getOSSBucketName
* @Description: 根据url获取bucketName
* @param fileUrl 文件url
* @return String bucketName
*/
private static String getOSSBucketName(String fileUrl){
String http = "http://";
String https = "https://";
int httpIndex = fileUrl.indexOf(http);
int httpsIndex = fileUrl.indexOf(https);
int startIndex = 0;
if(httpIndex==-1){
if(httpsIndex==-1){
return null;
}else{
startIndex = httpsIndex+https.length();
}
}else{
startIndex = httpIndex+http.length();
}
int endIndex = fileUrl.indexOf(".oss-");
return fileUrl.substring(startIndex, endIndex);
}
/**
*
* @MethodName: getFileName
* @Description: 根据url获取fileName
* @param fileUrl 文件url
* @return String fileName
*/
private static String getOSSFileName(String fileUrl){
String str = "aliyuncs.com/";
int beginIndex = fileUrl.indexOf(str);
if(beginIndex==-1) return null;
return fileUrl.substring(beginIndex+str.length());
}
/**
*
* @MethodName: getFileName
* @Description: 根据url获取fileNames集合
* @param fileUrl 文件url
* @return List fileName集合
*/
@SuppressWarnings("unused")
private static List getOSSFileName(List fileUrls){
List names = new ArrayList<>();
for (String url : fileUrls) {
names.add(getOSSFileName(url));
}
return names;
}
public static String testAddUploadFileInfo(String base64Img,String remotePath,String fileName){
try {
SerialBlob serialBlob = decodeToImage(base64Img);
InputStream binaryStream = serialBlob.getBinaryStream();
String url = OSSManageUtil.uploadFile(binaryStream, remotePath, fileName);
System.out.println(url);
return url;
}catch (Exception e) {
e.printStackTrace();
}
return "";
}
private static SerialBlob decodeToImage(String imageString) throws Exception {
BASE64Decoder decoder = new BASE64Decoder();
byte[] imageByte = decoder.decodeBuffer(imageString);
return new SerialBlob(imageByte);
}
控制层(以新增公寓图片为例)
public @ResponseBody String insertHouse(@RequestParam("input1") MultipartFile file1, HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//设施
String[] checkbox = multipartRequest.getParameterValues("ifacility");
String[] img = new String[1];
String savePath = "houseImg";
InputStream in = null;
try {
if (!file1.isEmpty()) {
in = file1.getInputStream();
img[0] = OSSManageUtil.uploadFile(in, savePath, file1.getOriginalFilename());
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
try {
int flag = house1.insertHouse(house);
if (flag > 0) {
YwHouPic pic = new YwHouPic();
int houseid = house1.selectHouId();
pic.setHouseid(houseid);
int f = houpic.insertHouImg(pic);
List<YwHouseFacility> list = new ArrayList<YwHouseFacility>();
if (f > 0) {
int ff=1;
if (checkbox != null) {
for (int i = 0; i < checkbox.length; i++) {
YwHouseFacility yhou = new YwHouseFacility();
yhou.setHouseid(houseid);
yhou.setFacilityid(Integer.parseInt(checkbox[i]));
list.add(yhou);
}
ff = house1.inFacility(list);
}
if (ff > 0) {
sysService.insertUserOperationRecod(getShiroUser(), "管理", "增加了编码为:" + houseid + "的");
return "success";
}
}
}
} catch (Exception e) {
e.printStackTrace();
return "fail";
}
return "fail";
}
oss图片下载(可直接取数据库中该字段的数据即可)
后端controllger:
@RequestMapping(value = "***.do", produces = "application/json;charset=utf-8")
public @ResponseBody String Houimage(String houseId) {
JSONObject json = new JSONObject();
try {
json = house1.queryByParam(Integer.parseInt(houseId));
} catch (Exception e) {
return "fail";
}
return json.toString();
}
后端service:
public JSONObject queryByParam(int houseId) {
JSONObject jsonObject = new JSONObject();
List<YwHouseFacility> list = houseMapper.queryFacility(houseId);
House h = houseMapper.queryHouse(houseId);
List<AreaMessage> list2 = houseMapper.queryArea(h.getAreaId());
HouseMessage house = new HouseMessage();
List<HouseMessage> list1= new ArrayList<HouseMessage>();
int[] fa = new int[10];
for (int i = 0; i < list.size(); i++) {
fa[i] = list.get(i).getFacilityid();
}
house.setHouimage1(h.getHouimage1());
list1.add(house);
jsonObject.put("house", list1);
jsonObject.put("area", list2);
return jsonObject;
}
前端js:
function showHouse(id){
$.ajax({
url:'/sys/ywhouse/getHouse.do',
type:'post',
data:{
"houseId":id,
},
async:false,
datatype:'json',
success:function(data){
setTimeout(function () {
if ((data.house[0].houimage1!="http://localhost:8080/images/image1.png")&&(data.house[0].houimage1!="")&&(data.house[0].houimage1!=null)) {
//给img1赋值
$("#img1").attr('src',data.house[0].houimage1);
$("#delete1").css('display','block');
}
},200);
var obj = document.getElementsByName("facility");
for (var j = 0; j < data.house[0].facilityid.length; j++) {
for (var i = 0; i < obj.length; i++) {
if (obj[i].value==data.house[0].facilityid[j]) {
obj[i].checked="checked";
}
}
}
}
});
}
前端页面:
class="row_line col-lg-3 col-md-3 col-sm-3 col-xs-12">