今天遇到需求,用Java完成图片上传,网搜之后,大神们早就做过,个人总结一下。
目标:借助commons-fileupload工具包,使用Java语言实现spring-mvc文件上传U盘云,返回的是上传U盘云的一个链接,这样你在浏览器中输入链接就可以直接访问了。
主要实现:
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxInMemorySize">
<value>1638400</value>
</property>
<property name="defaultEncoding" value="UTF-8" />
</bean>
图片上传核心接口
public Map<String, Object> saveImage(ImageForm form)
throws IOException {
MultipartFile image = form.getImageFile();
//获取图片类型
String imgFormat = image.getContentType();
byte[] imageByteData = image.getBytes();
Map<String, String> result = new HashMap<String, String>();
result.put("result", Constants.ERR);
//u盘云链接拼接
String accessUrl = "/" + System.currentTimeMillis()
+ RandomUtils.genRandomStr(10) + "." + imgFormat;
UpYun upyun = new UpYun(bucketname, username, password);//上传U盘云
boolean isSuccess = upyun.writeFile(accessUrl, imageByteData, true, null);
if (isSuccess) {
result.put("result", Constants.OK);
result.put("picOrignalPath", imgurl + accessUrl);
}
Map<String,Object> message = new HashMap<>();
if (Constants.OK.equals(result.get("result"))) {
message.put("data", result.get("picOrignalPath"));// 返回原图路径
}else{
return WebUtils.errorMessage("result", "图片上传失败");
}
return message;
}
writeFile()方法封装
/**
* 上传文件
*
* @param filePath 文件路径(包含文件名)
* @param datas 文件内容
* @param auto 是否自动创建父级目录(最多10级)
* @param params 额外参数
*
* @return true or false
*/
public boolean writeFile(String filePath, byte[] datas, boolean auto,
Map<String, String> params) {
return HttpAction(METHOD_PUT, formatPath(filePath), datas, null, auto, params) != null;
}
HttpAction()方法封装
/**
* 连接处理逻辑
*
* @param method 请求方式 {GET, POST, PUT, DELETE}
* @param uri 请求地址
* @param datas 该请求所需发送数据(可为 null)
* @param outFile 文件描述符(可为 null)
* @param auto 自动创建父级目录(最多10级)
* @param params 额外参数
*
* @return 请求结果(字符串)或 null
*/
private String HttpAction(String method, String uri, byte[] datas, File outFile, boolean auto,
Map<String, String> params) {
String result = null;
HttpURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
// 获取链接
URL url = new URL("http://" + apiDomain + uri);
conn = (HttpURLConnection) url.openConnection();
// 设置必要参数
conn.setConnectTimeout(timeout);
conn.setRequestMethod(method);
conn.setUseCaches(false);
if (!method.equals(METHOD_DELETE) && !method.equals(METHOD_HEAD)
&& !method.equals(METHOD_GET)) {
conn.setDoOutput(true);
}
// 设置时间
conn.setRequestProperty(DATE, getGMTDate());
// 是否自动创建父级目录
if (auto) {
conn.setRequestProperty(MKDIR, "true");
}
long contentLength = 0;
if (datas == null) {
conn.setRequestProperty(CONTENT_LENGTH, "0");
} else {
contentLength = datas.length;
conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(datas.length));
// 设置文件的 MD5 参数
if (!isEmpty(this.contentMD5)) {
conn.setRequestProperty(CONTENT_MD5, this.contentMD5);
this.contentMD5 = null;
}
// 设置文件的访问密钥
if (!isEmpty(this.fileSecret)) {
conn.setRequestProperty(CONTENT_SECRET, this.fileSecret);
this.fileSecret = null;
}
}
// 设置签名
conn.setRequestProperty(AUTHORIZATION, sign(conn, uri, contentLength));
// 是否是创建文件目录
boolean isFolder = false;
// 设置额外的参数,如图片缩略图等
if (params != null && !params.isEmpty()) {
isFolder = !isEmpty(params.get(PARAMS.KEY_MAKE_DIR.getValue()));
for (Map.Entry<String, String> param : params.entrySet()) {
conn.setRequestProperty(param.getKey(), param.getValue());
}
}
// 创建链接
conn.connect();
if (datas != null) {
os = conn.getOutputStream();
os.write(datas);
os.flush();
}
if (isFolder) {
os = conn.getOutputStream();
os.flush();
}
if (outFile == null) {
result = getText(conn, METHOD_HEAD.equals(method));
} else {
result = "";
os = new FileOutputStream(outFile);
byte[] data = new byte[4096];
int temp = 0;
is = conn.getInputStream();
while ((temp = is.read(data)) != -1) {
os.write(data, 0, temp);
}
}
} catch (IOException e) {
if (debug)
LOG.error(e.getMessage(), e);
// 操作失败
return null;
} finally {
try {
if (os != null) {
os.close();
os = null;
}
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return result;
}
这样你会获得一个类似这样的链接:
http://pod-new-dev.b0.upaiyun.com/1503914536631FMIlF5Dhmh.image/png
直接在网页上打开就好啦!