**关于在实际开发中最常用也是用的最多的Java实现文档、图片上传。**
*一、准备阶段*
文档、图片上传有几种方式,包括传统的ajax上传,云上传,这里给大家实现通过代码将图片上传至七牛云服务器并返回图片地址。
1.需申请一台七牛云服务器地址(可免费试用30天)
![](https://img-blog.csdnimg.cn/20200731134344400.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMzg4NjU0,size_16,color_FFFFFF,t_70)

==注册登陆成功后可申请试用30天,点击空间管理,即可新增空间==![](https://img-blog.csdnimg.cn/20200731134522292.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMzg4NjU0,size_16,color_FFFFFF,t_70)
==新增成功点击进空间,会给你个测试域名用来返回图片地址调用,当然可以添加自己的域名,具体参考七牛云服务器描述==


*二、代码准备*
只需要提供接口controller以及业务service包即可
**话不多说!上代码!**

```java
package com.ymzd.shop.controller.fileupload;


import com.ymzd.shop.service.IUploadService;
import com.ymzd.shop.common.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
* @author wangzhic
* @date 2019-12
*/
@RestController
@RequestMapping("/upload")
@Api(tags = "文件上传接口", description = "wangzhicheng")
public class UploadController {

@Resource
private IUploadService uploadServiceImpl;


/**
* 获取七牛云的token
*
* @return
*/
@GetMapping("/gettoken")
@ApiOperation(value = "获取上传token", notes = "获取token无需要参数")
public ResultData<String> getUpToken() {

String upToken = uploadServiceImpl.getUpToken();
if (upToken != null && upToken.length() != 0) {
return new ResultData<String>().success(upToken);
} else {
return new ResultData<String>().error("token获取失败!");
}
}

/**
* 上传文件到七牛云服务器
*
* @param files
* @param request
* @return
*/
@PostMapping(value = "/files", headers = "content-type=multipart/form-data")
@ApiOperation(value = "文件上传接口", notes = "文件上传api必须用表单方式提交")
public ResultData<String> upLoadFile(@ApiParam(value = "files", required = true)
@RequestParam("files") MultipartFile[] files,
HttpServletRequest request) {
String url = "";
if (files.length == 1) {
if (files[0].getSize() > 5 * 1024 * 1024) {
return new ResultData<String>().error("单个图片不能大于5M!");
} else {
try {
url = uploadServiceImpl.uploadFile(files[0]);
//return new ResultData<String>().success(url);
} catch (Exception e) {
return new ResultData<String>().error("图片大于5M,请重新上传!");
}
}
} else {
for (MultipartFile file : files) {
if (StringUtils.isEmpty(file)) {
return new ResultData<String>().error("文件为空请重新上传!");
} else if (file.getSize() > 5 * 1024 * 1024) {
return new ResultData<String>().error("单个图片不能大于5M!");
} else {
try {
url += uploadServiceImpl.uploadFile(file) + " ";
System.out.println("回调地址:" + url);
} catch (Exception e) {
return new ResultData<String>().error("图片大于5M,请重新上传!");
}
}
}
}
return new ResultData<String>().success(url);

}
}

 

```
可设置上传大小,这里我设置了单个图片不能超过5M

```java
servlet:
multipart:
max-file-size: 25MB
max-request-size: 50MB
```
该配置表示单个文件不超过25M 单个请求的总文件大小不超过 50M

```java
package com.ymzd.shop.service.impl;


import com.ymzd.shop.service.IUploadService;
import com.ymzd.shop.util.QiniuCloudUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@Service
public class UploadServiceImpl implements IUploadService {

/**
* 获取七牛云token
*
* @return
*/
@Override
public String getUpToken() {
return QiniuCloudUtil.getupToken();
}

/**
* 上传文件到七牛云
*
* @param file
*/
@Override
public String uploadFile(MultipartFile file) throws Exception {
byte[] bytes = null;
System.out.println("fileName="+file.getOriginalFilename());
try {
bytes = file.getBytes();
} catch (IOException e) {
e.printStackTrace();
}
return QiniuCloudUtil.uploadFileBytes(bytes,file.getOriginalFilename());
}

}

```
业务块代码

```java
package com.ymzd.shop.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class QiniuCloudUtil {
private static Properties properties = new Properties();
// 设置七牛云账号的AK和SK
private static String ACCESS_KEY = null;
private static String SECRET_KEY = null;
// 要上传的空间bucket
private static String BUCKET = null;
//外链地址:这里要改成自己的域名
private static String DOMAIN = null;

private static SimpleDateFormat simpleDateFormat;

private static int i = 1;

static {
try {
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("qiniuyun.properties"));
ACCESS_KEY = properties.getProperty("accessKey");
SECRET_KEY = properties.getProperty("secretKey");
BUCKET = properties.getProperty("hostname");
DOMAIN = properties.getProperty("DOMAIN");
simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
} catch (IOException e) {
e.printStackTrace();
}
}


/**
* 获取七牛云Token
*/
public static String getupToken() {
//秘钥配置上传的凭证
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
StringMap putPolicy = new StringMap();
putPolicy.put("returnBody", "{\"fileUrl\": \"" + DOMAIN + "$(key)\"}");//上传成功后是返回这个json数据,fileUrl就是的地址
long expireSeconds = 3600;//过期时间

String upToken = auth.uploadToken(BUCKET, null, expireSeconds, putPolicy);
System.out.println(upToken);
return upToken;
}

/**
* @param
* @return 外键地址
*/
//普通上传
public static String uploadFile() {
//文件的外链地址
StringBuffer fileUrl = new StringBuffer(DOMAIN);

//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone2());

UploadManager uploadManager = new UploadManager(cfg);

//如果是Windows情况下,格式是 D:\\qiniu\\test.png
String localFilePath = "/Users/leeyunt/Downloads/1864602-3d5d1de100e459b8.png";
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;

try {
//上传文件
Response response = uploadManager.put(localFilePath, key, getupToken());

//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
fileUrl.append(putRet.key);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
return fileUrl.toString();
}

//base64方式上传
public static String uploadFileBase64(byte[] base64, String key) throws Exception {
String file64 = Base64.encodeToString(base64, 0);
Integer l = base64.length;
String uploadUrl = "http://up-z2.qiniup.com/putb64/" + l + "/key/" + UrlSafeBase64.encodeToString(key);
//非华南空间需要修改上传域名
//上传文件
RequestBody rb = RequestBody.create(null, file64);
Request request = new Request.Builder().
url(uploadUrl)
.addHeader("Content-Type", "application/octet-stream")
.addHeader("Authorization", "UpToken " + getupToken())
.post(rb).build();
//System.out.println(request.headers());
OkHttpClient client = new OkHttpClient();
okhttp3.Response response = client.newCall(request).execute();
System.out.println(response);
return DOMAIN + key;
}

//字节数组上传

/**
* 字节上传
*
* @param uploadBytes
* @param fileName
* @return 链接地址
* @throws Exception
*/
public static String uploadFileBytes(byte[] uploadBytes, String fileName) throws Exception {
//文件的外链地址
StringBuffer fileUrl = new StringBuffer("https://"+DOMAIN);

//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone2());

UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下,以文件内容的hash值作为文件名
//System.out.println("截取文件:"+fileName.substring(fileName.indexOf(".")));

String key = simpleDateFormat.format(new Date())+ i + fileName.substring(fileName.indexOf("."));

i++;
//秘钥配置上传的凭证
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
String upToken = auth.uploadToken(BUCKET);

try {
//上传文件
Response response = uploadManager.put(uploadBytes, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
fileUrl.append("/" + putRet.key);
//MyPutRet myPutRet=response.jsonToObject(MyPutRet.class);
//System.out.println(myPutRet);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
return fileUrl.toString();
}

}

```
这里附上工具类,经过我不断发现问题,多次加工完成,我所返回的地址为“https”的加密路径,所以七牛云必须配置自己的域名。
上传差不多就这个,返回的字符即是图片地址,即可访问。==盆友开始编码吧!==

posted on 2020-07-31 14:15  square凉  阅读(1300)  评论(0编辑  收藏  举报