如何用mendix连接oss上传文件
首先我们先创建一个mendix项目,我的版本是8.18.5,然后创建四个常量,AccessKey ID(id),AccessKey Secret(密钥),Bucket(oss名称),Endpoint(区域地址),
如何申请这oss请参考:点击此处查看
右键文件夹,点击add other ,点击constant,这个就是新建一个常量的步骤
这个就是获取Endpoint的方式
新建一个domain model ,该实体继承Filedocument,然后新增一个字段url用来储存文件路径
ok,现在我们来画页面布局,首先外面套一个dataview,选择我们刚刚创建的那个实体,然后拉一个filemanager,这个用来选择文件上传(图中带file的组件),右边的name是一个文本框,用来显示文件名称,没啥用,然后加一个按钮用来调用微流,进行上传
这里是按钮调用的微流,这里面调用了一个javaction(此处上传文件返回一个urll路径),后面的change事件用来修改该该对象的url,下图为javaction需要的参数
url拼接
public String upload(IMendixObject __Image) {
String url = "";
try {
//获取传来对象的id
long id = __Image.getId().toLong();
//获取该文件命名
String imageName = __Image.getValue(getContext(), "Name");
// 获取文件类型
String fileType = imageName.substring(imageName.lastIndexOf("."));
// 编写文件新名称
String newFileName = id + fileType;
// 构建日期路径, 例如:OSS目标文件夹/2020/10/31/文件名
String filePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
//图片压缩到500k以内
InputStream inputStream = Core.getFileDocumentContent(getContext(), __Image);
ByteArrayOutputStream output = new ByteArrayOutputStream();
//文件大小的btye数组
byte[] buffer = new byte[4096];
int n = 0;
//写出
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
// BufferedImage src=ImageIO.read(inputStream);
//按指定大小压缩图片
byte[] bs = compressPicForScale(output.toByteArray(),500);
//字节数组输入流,
ByteArrayInputStream inputStream2 = new ByteArrayInputStream(bs);
//拼接的路径
String objName = filePath + "/" + newFileName;
//调用上传方法
boolean isSuc = putFile(objName, inputStream2);
if (isSuc) {
url += "https://" + bucketName + "." + endpoint + "/" + objName;
} else {
url= "error";
}
inputStream.close();
} catch (Exception e) {
//e.printStackTrace();
}
//把开始的;去掉
if(!url.equals("error") && url!="") {
}else if(url==""){
url="error";
}
return url;
}
上传方法
private boolean putFile(String objectName, InputStream inputStream) {
boolean isSuc = false;
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// 设置代理服务器端口。
// if (!myfirstmodule.proxies.constants.Constants.getOssProxyHost().equals("error")) {
// conf.setProxyHost(myfirstmodule.proxies.constants.Constants.getOssProxyHost());
// }
// if (myfirstmodule.proxies.constants.Constants.getOssProxyPort() != -1) {
// conf.setProxyPort(myfirstmodule.proxies.constants.Constants.getOssProxyPort().intValue());
// }
// conf.setProtocol(Protocol.HTTP);
//创建一个实列,用来上传
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
//上传
ObjectMetadata objectMetadata = new ObjectMetadata();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
putObjectRequest.setMetadata(objectMetadata);
ossClient.putObject(putObjectRequest);
isSuc = true;
} catch (Exception e) {
isSuc = false;
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return isSuc;
}
这里是我整个javaction
// This file was generated by Mendix Studio Pro.
//
// WARNING: Only the following code will be retained when actions are regenerated:
// - the import list
// - the code between BEGIN USER CODE and END USER CODE
// - the code between BEGIN EXTRA CODE and END EXTRA CODE
// Other code you write will be lost the next time you deploy the project.
// Special characters, e.g., é, ö, à, etc. are supported in comments.
package myfirstmodule.actions;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.mendix.core.Core;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;
import net.coobird.thumbnailator.Thumbnails;
import com.mendix.systemwideinterfaces.core.IMendixObject;
public class Upload extends CustomJavaAction<java.lang.String>
{
private IMendixObject __Parameter;
private system.proxies.FileDocument Parameter;
public Upload(IContext context, IMendixObject Parameter)
{
super(context);
this.__Parameter = Parameter;
}
@java.lang.Override
public java.lang.String executeAction() throws Exception
{
this.Parameter = __Parameter == null ? null : system.proxies.FileDocument.initialize(getContext(), __Parameter);
// BEGIN USER CODE
return upload(__Parameter);
//throw new com.mendix.systemwideinterfaces.MendixRuntimeException("Java action was not implemented");
// END USER CODE
}
/**
* Returns a string representation of this action
*/
@java.lang.Override
public java.lang.String toString()
{
return "Upload";
}
// BEGIN EXTRA CODE
String endpoint = myfirstmodule.proxies.constants.Constants.getEndpoint();
String accessKeyId = myfirstmodule.proxies.constants.Constants.getAccessKeyID();
String accessKeySecret = myfirstmodule.proxies.constants.Constants.getAccessKeySecret();
// 获取oss的Bucket名称
String bucketName = myfirstmodule.proxies.constants.Constants.getBucket();
/**
* 判断之前是否有上传图片如果有的话就删除在上传
* @param originalUrl
* @return
*/
public String judge(String originalUrl,IMendixObject __Image) {
//之前有上传,先删除之前的,在上传
if(originalUrl!=null && !originalUrl.equals("")) {
List<String> list=new ArrayList<>();
if(!originalUrl.contains(";")) {
list.add(originalUrl);
}else {
String[] split = originalUrl.split(";");
list=Arrays.asList(split);
}
delete(list);
}
return upload(__Image);
}
/**
* 删除之前的图片
* @param url
*/
public void delete(List<String> url) {
try {
for (String string : url) {
// 填写文件完整路径。文件完整路径中不能包含Bucket名称。
String objectName = string.substring(string.lastIndexOf("com/")+4);
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 删除文件或目录。如果要删除目录,目录必须为空。
ossClient.deleteObject(bucketName, objectName);
// 关闭OSSClient。
ossClient.shutdown();
}
} catch (Exception e) {
Core.getLogger("文件删除异常").error(e);
}
}
public String upload(IMendixObject __Image) {
String url = "";
try {
//获取传来对象的id
long id = __Image.getId().toLong();
//获取该文件命名
String imageName = __Image.getValue(getContext(), "Name");
// 获取文件类型
String fileType = imageName.substring(imageName.lastIndexOf("."));
// 编写文件新名称
String newFileName = id + fileType;
// 构建日期路径, 例如:OSS目标文件夹/2020/10/31/文件名
String filePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
//图片压缩到500k以内
InputStream inputStream = Core.getFileDocumentContent(getContext(), __Image);
ByteArrayOutputStream output = new ByteArrayOutputStream();
//文件大小的btye数组
byte[] buffer = new byte[4096];
int n = 0;
//写出
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
// BufferedImage src=ImageIO.read(inputStream);
//按指定大小压缩图片
byte[] bs = compressPicForScale(output.toByteArray(),500);
//字节数组输入流,
ByteArrayInputStream inputStream2 = new ByteArrayInputStream(bs);
//拼接的路径
String objName = filePath + "/" + newFileName;
//调用上传方法
boolean isSuc = putFile(objName, inputStream2);
if (isSuc) {
url += "https://" + bucketName + "." + endpoint + "/" + objName;
} else {
url= "error";
}
inputStream.close();
} catch (Exception e) {
//e.printStackTrace();
}
//把开始的;去掉
if(!url.equals("error") && url!="") {
}else if(url==""){
url="error";
}
return url;
}
private boolean putFile(String objectName, InputStream inputStream) {
boolean isSuc = false;
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// 设置代理服务器端口。
// if (!myfirstmodule.proxies.constants.Constants.getOssProxyHost().equals("error")) {
// conf.setProxyHost(myfirstmodule.proxies.constants.Constants.getOssProxyHost());
// }
// if (myfirstmodule.proxies.constants.Constants.getOssProxyPort() != -1) {
// conf.setProxyPort(myfirstmodule.proxies.constants.Constants.getOssProxyPort().intValue());
// }
// conf.setProtocol(Protocol.HTTP);
//创建一个实列,用来上传
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
//上传
ObjectMetadata objectMetadata = new ObjectMetadata();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
putObjectRequest.setMetadata(objectMetadata);
ossClient.putObject(putObjectRequest);
isSuc = true;
} catch (Exception e) {
isSuc = false;
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return isSuc;
}
private static final Integer ZERO = 0;
private static final Integer ONE_ZERO_TWO_FOUR = 1024;
private static final Integer NINE_ZERO_ZERO = 900;
private static final Integer THREE_TWO_SEVEN_FIVE = 3275;
private static final Integer TWO_ZERO_FOUR_SEVEN = 2047;
private static final Double ZERO_EIGHT_FIVE = 0.85;
private static final Double ZERO_SIX = 0.6;
private static final Double ZERO_FOUR_FOUR = 0.44;
private static final Double ZERO_FOUR = 0.4;
/**
* 根据指定大小压缩图片
*
* @param imageBytes 源图片字节数组
* @param desFileSize 指定图片大小,单位kb
* @return 压缩质量后的图片字节数组
*/
public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
if (imageBytes == null || imageBytes.length <= ZERO || imageBytes.length < desFileSize * ONE_ZERO_TWO_FOUR) {
return imageBytes;
}
long srcSize = imageBytes.length;
double accuracy = getAccuracy(srcSize / ONE_ZERO_TWO_FOUR);
// double accuracy =desFileSize * ONE_ZERO_TWO_FOUR;
try {
while (imageBytes.length > desFileSize * ONE_ZERO_TWO_FOUR) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream).scale(accuracy).outputQuality(accuracy).toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
// Core.getLogger("缩略图大小 ").error(imageBytes.length/1024);
}
} catch (Exception e) {
}
return imageBytes;
}
/**
* 自动调节精度(经验数值)
*
* @param size 源图片大小
* @return 图片压缩质量比
*/
private static double getAccuracy(long size) {
double accuracy;
if (size < NINE_ZERO_ZERO) {
accuracy = ZERO_EIGHT_FIVE;
} else if (size < TWO_ZERO_FOUR_SEVEN) {
accuracy = ZERO_SIX;
} else if (size < THREE_TWO_SEVEN_FIVE) {
accuracy = ZERO_FOUR_FOUR;
} else {
accuracy = ZERO_FOUR;
}
return accuracy;
}
// END EXTRA CODE
}
以上就是上传到oss的流程,该文件我以图片为例,jar如下
<!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.14</version>
</dependency>