2019-08-07更新 增加API接口

This commit is contained in:
Hellohao
2019-08-07 23:22:44 +08:00
parent 77efdc9fa6
commit d777f42719
69 changed files with 7374 additions and 329 deletions
@@ -38,11 +38,13 @@ public class AdminController {
private ImgreviewService imgreviewService;
@Autowired
private ConfigService configService;
@Autowired
private UploadConfigService uploadConfigService;
@RequestMapping(value = "/goadmin")
public String goadmin1(HttpSession session, Model model, HttpServletRequest request) {
User user = (User) session.getAttribute("user");
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
if(user!=null){
if (user.getLevel() == 1) {
model.addAttribute("level", "普通用户");
@@ -53,6 +55,7 @@ public class AdminController {
}
model.addAttribute("levels", user.getLevel());
model.addAttribute("username", user.getUsername());
model.addAttribute("api", uploadConfig.getApi());
return "admin/index";
}else{
return "redirect:/";
@@ -331,7 +334,17 @@ public class AdminController {
// -1 用户名重复
return jsonArray.toString();
}
//进入api
@RequestMapping(value = "/toapi")
public String toapi(HttpSession session, Model model, HttpServletRequest request) {
User u = (User) session.getAttribute("user");
Config config = configService.getSourceype();
//key信息
model.addAttribute("username", u.getUsername());
model.addAttribute("level", u.getLevel());
model.addAttribute("domain", config.getDomain());
return "admin/api";
}
@GetMapping(value = "/images/{id}")
@ResponseBody
@@ -0,0 +1,227 @@
package cn.hellohao.controller;
import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.service.impl.*;
import cn.hellohao.utils.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Hellohao
* @version 1.0
* @date 2019-07-18 17:22
*/
@RestController
public class ClientController {
@Autowired
private NOSImageupload nOSImageupload;
@Autowired
private UserService userService;
@Autowired
private KeysService keysService;
@Autowired
private OSSImageupload ossImageupload;
@Autowired
private ConfigService configService;
@Autowired
private USSImageupload ussImageupload;
@Autowired
private KODOImageupload kodoImageupload;
@Autowired
private UploadConfigService uploadConfigService;
@Autowired
private NoticeService noticeService;
@Autowired
private COSImageupload cosImageupload;
@Autowired
private FTPImageupload ftpImageupload;
@Value("${systemupdate}")
private String systemupdate;
@PostMapping(value = "/clientupimg")
@ResponseBody
public ResultBean clientupimg(@RequestParam("file") List<MultipartFile> file, String email, String pass) throws Exception {
ResultBean resultBean = null;
JSONArray jsonArray = new JSONArray();
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
if (uploadConfig.getApi() == 1) {
if (email != null && pass != null) {
Integer ret = userService.login(email, pass);
if (ret > 0) {
User user = userService.getUsers(email);
if (user.getIsok() == 1) {
User u = userService.getUsers(email);
Config config = configService.getSourceype();//查询当前系统使用的存储源类型。
Keys key = keysService.selectKeys(config.getSourcekey());
if (key.getStorageType() != 0 && key.getStorageType() != null) {
if (key.getStorageType() == 1) {
nOSImageupload.Initialize(key);//实例化网易
} else if (key.getStorageType() == 2) {
OSSImageupload.Initialize(key);
} else if (key.getStorageType() == 3) {
USSImageupload.Initialize(key);
} else if (key.getStorageType() == 4) {
KODOImageupload.Initialize(key);
} else if (key.getStorageType() == 6) {
COSImageupload.Initialize(key);
} else if (key.getStorageType() == 7) {
FTPImageupload.Initialize(key);
} else {
System.err.println("客户端:未获取到对象存储参数,初始化失败。");
}
}
Print.Normal("客户端:初始化上传。");
Boolean b = false;
if (config.getSourcekey() == 5) {
b = true;
} else {
b = StringUtils.doNull(config.getSourcekey(), key);//判断对象是否有空值
}
if (b) {
long stime = System.currentTimeMillis();
String userpath = "tourist";
if (uploadConfig.getUrltype() == 2) {
java.text.DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
userpath = dateFormat.format(new Date());
} else {
if (u != null) {
userpath = u.getUsername();
}
}
Map<String, MultipartFile> map = new HashMap<>();
for (MultipartFile multipartFile : file) {
//获取文件名
System.out.println(multipartFile.toString());
String fileName = multipartFile.getOriginalFilename();
String lastname = fileName.substring(fileName.lastIndexOf(".") + 1);//获取文件后缀
if (!multipartFile.isEmpty()) { //判断文件是否为空
map.put(lastname, multipartFile);
}
}
Map<ReturnImage, Integer> m = null;
Map<ReturnImage, Integer> m2 = null;
if (key.getStorageType() == 1) {
m = nOSImageupload.clientuploadNOS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 2) {
m = ossImageupload.clientuploadOSS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 3) {
m = ussImageupload.clientuploadUSS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 4) {
m = kodoImageupload.clientuploadKODO(map, userpath, uploadConfig);
} else if (key.getStorageType() == 5) {
m2 = LocUpdateImg.clientuploadFTP(map, userpath, uploadConfig);
} else if (key.getStorageType() == 6) {
m = cosImageupload.clientuploadCOS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 7) {
m = ftpImageupload.clientuploadFTP(map, userpath, uploadConfig);
} else {
System.err.println("未获取到对象存储参数,上传失败。");
}
Images img = new Images();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String times = df.format(new Date());
System.out.println("上传图片的时间是:" + times);
if (key.getStorageType() == 5) {
for (Map.Entry<ReturnImage, Integer> entry : m2.entrySet()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Imgname", entry.getKey().getImgname());
if (key.getStorageType() == 5) {
if (config.getDomain() != null) {
jsonObject.put("Imgurl", config.getDomain() + "/links/" + entry.getKey().getImgurl());
img.setImgurl(config.getDomain() + "/links/" + entry.getKey().getImgurl());//图片链接
} else {
jsonObject.put("Imgurl", config.getDomain() + "/links/" + entry.getKey().getImgurl());
img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() + "/links/" + entry.getKey().getImgurl());//图片链接
}
} else {
jsonObject.put("Imgname", entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());//图片链接
}
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);//用户id
} else {
img.setUserid(u.getId());//用户id
}
img.setSizes((entry.getValue()));
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(0);
//-1证明超出大小,
if (entry.getValue() != -1) {
userService.insertimg(img);
}
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
jsonArray.add(jsonObject);
}
} else {
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Imgname", entry.getKey().getImgname());
if (key.getStorageType() == 5) {
if (config.getDomain() != null) {
jsonObject.put("Imgurl", config.getDomain() + "/links/" + entry.getKey().getImgurl());
img.setImgurl(config.getDomain() + "/links/" + entry.getKey().getImgurl());//图片链接
} else {
jsonObject.put("Imgurl", config.getDomain() + "/links/" + entry.getKey().getImgurl());
img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() + "/links/" + entry.getKey().getImgurl());//图片链接
}
} else {
jsonObject.put("Imgurl", entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());//图片链接
}
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);//用户id
} else {
img.setUserid(u.getId());//用户id
}
img.setSizes((entry.getValue()));
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(0);
//-1证明超出大小,
if (entry.getValue() != -1) {
userService.insertimg(img);
}
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
jsonArray.add(jsonObject);
}
}
//上传成功
resultBean = ResultBean.success(jsonArray);
} else {resultBean = ResultBean.error(-1, "服务器内部错误,请联系管理员");}
}
} else {resultBean = ResultBean.error(-2, "此用户信息不正确。");}
} else {resultBean = ResultBean.error(-3, "邮箱密码为空");}
}
else{resultBean = ResultBean.error(-4, "管理员关闭了API接口");}
//return jsonArray.toString();
return resultBean;
}
@GetMapping (value = "/notices")
@ResponseBody
public String notices() throws Exception {
return "-1";//-1就是没有公告,客户端不显示
}
}
@@ -0,0 +1,68 @@
package cn.hellohao.controller;
import cn.hellohao.exception.StorageSourceInitException;
import cn.hellohao.utils.Print;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import java.net.SocketException;
import java.util.Date;
import java.util.List;
/**
* @author Hellohao
* @version 1.0
* @date 2019/8/6 8:57
*/
@ControllerAdvice
public class ExceptionHandling {
@ExceptionHandler
//@ResponseBody
public ModelAndView test(StorageSourceInitException ssie){
ModelAndView modelAndView = new ModelAndView("index");
Print.Normal("异常拦截成功:"+ ssie.getMessage());
modelAndView.addObject("error",ssie.getMessage());
//返回错误信息,并显示给用户
return modelAndView;
}
@ExceptionHandler
public String test4(SocketException e){
ModelAndView modelAndView = new ModelAndView("/index");
Print.Normal("存储源配置不正确,初始化失败"+ e.getMessage());
modelAndView.addObject("error",e.getMessage());
//返回错误信息,并显示给用户
return e.getMessage();
}
@ExceptionHandler
public String test3(Exception e){
ModelAndView modelAndView = new ModelAndView("/index");
Print.Normal("系统内部错误:"+ e.getMessage());
modelAndView.addObject("error",e.getMessage());
//返回错误信息,并显示给用户
return e.getMessage();
}
// @ExceptionHandler
// public String methodArgumentNotValid(BindException e) {
// List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
// StringBuilder errorMessage = new StringBuilder();
// for (int i = 0; i < allErrors.size(); i++) {
// ObjectError error = allErrors.get(i);
// errorMessage.append(error.getDefaultMessage());
// if (i != allErrors.size() - 1) {
// errorMessage.append(", ");
// }
// }
// // do something
// System.out.println(errorMessage.toString());// 这里面是错误信息
// return errorMessage.toString();
// }
}
@@ -6,6 +6,7 @@ import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import cn.hellohao.exception.StorageSourceInitException;
import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.service.impl.*;
@@ -65,27 +66,28 @@ public class UpdateImgController {
key= keysService.selectKeys(config.getSourcekey());//然后根据类型再查询key
//b = StringUtils.doNull(key);//判断对象是否有空值
if(key.getStorageType()!=0 && key.getStorageType()!=null){
int ret =0;
if(key.getStorageType()==1){
nOSImageupload.Initialize(key);//实例化网易
ret =nOSImageupload.Initialize(key);//实例化网易
}else if (key.getStorageType()==2){
OSSImageupload.Initialize(key);
ret =OSSImageupload.Initialize(key);
}else if(key.getStorageType()==3){
USSImageupload.Initialize(key);
ret = USSImageupload.Initialize(key);
}else if(key.getStorageType()==4){
KODOImageupload.Initialize(key);
ret = KODOImageupload.Initialize(key);
}else if(key.getStorageType()==6){
COSImageupload.Initialize(key);
ret = COSImageupload.Initialize(key);
}else if(key.getStorageType()==7){
FTPImageupload.Initialize(key);
ret = FTPImageupload.Initialize(key);
}
else{
Print.Normal("为获取到存储参数,或者使用存储源是本地的。");
}
if(ret<1){model.addAttribute("error", "当前存储源参数配置不完整,请联系管理员配置存储源。");}
else{model.addAttribute("error", 1);}
}
}
//if(b){
//}
User u = (User) httpSession.getAttribute("user");
String email = (String) httpSession.getAttribute("email");
if (email != null) {
@@ -114,7 +116,6 @@ public class UpdateImgController {
Integer isupdate = 1;
if(uploadConfig.getIsupdate()!=1){
isupdate = (u == null) ? 0: 1;//如果u等于null那么isupdate就等于0,否则等于1
//isupdate=0;
}
model.addAttribute("ykxz", isupdate);
return "index";
@@ -7,6 +7,7 @@ import java.util.UUID;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import cn.hellohao.pojo.Config;
import cn.hellohao.pojo.EmailConfig;
@@ -39,7 +40,7 @@ public class UserController {
@RequestMapping("/register")
@ResponseBody
public String Register(User user) {
public String Register(@Valid User user) {
//取当前时间
JSONObject jsonObject = new JSONObject();
EmailConfig emailConfig = emailConfigService.getemail();
@@ -82,9 +83,10 @@ public class UserController {
return jsonObject.toString();
}
@RequestMapping("/login.do")
@ResponseBody
public String login(HttpServletRequest request, HttpSession httpSession, String email, String password) {
public String login( HttpSession httpSession, String email, String password) {
JSONArray jsonArray = new JSONArray();
Integer ret = userService.login(email, password);
@@ -0,0 +1,27 @@
package cn.hellohao.exception;
/**
* @author Tiansh
* @version 1.0
* @date 2019/8/7 9:02
*/
public class LoginException extends RuntimeException {
public LoginException() {
}
public LoginException(String message) {
super(message);
}
public LoginException(String message, Throwable cause) {
super(message, cause);
}
public LoginException(Throwable cause) {
super(cause);
}
public LoginException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -0,0 +1,29 @@
package cn.hellohao.exception;
/**
* @author Hellohao
* @version 1.0
* @date 2019/8/6 8:51
*/
//创建自定义异常
//
public class StorageSourceInitException extends RuntimeException {
public StorageSourceInitException() {
}
public StorageSourceInitException(String message) {
super(message);
}
public StorageSourceInitException(String message, Throwable cause) {
super(message, cause);
}
public StorageSourceInitException(Throwable cause) {
super(cause);
}
public StorageSourceInitException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -0,0 +1,56 @@
package cn.hellohao.pojo;
public class ResultBean {
private int code;
private String msg;
private Object data;
private ResultBean() {
}
public static ResultBean error(int code, String msg) {
ResultBean resultBean = new ResultBean();
resultBean.setCode(code);
resultBean.setmsg(msg);
return resultBean;
}
public static ResultBean success() {
ResultBean resultBean = new ResultBean();
resultBean.setCode(0);
resultBean.setmsg("success");
return resultBean;
}
public static ResultBean success(Object data) {
ResultBean resultBean = new ResultBean();
resultBean.setCode(200);
resultBean.setmsg("success");
resultBean.setData(data);
return resultBean;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getmsg() {
return msg;
}
public void setmsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
@@ -8,11 +8,12 @@ public class UploadConfig {
private Integer imgcountuser;
private Integer urltype;
private Integer isupdate;
private Integer api;
public UploadConfig() {
}
public UploadConfig(String suffix, Integer filesizetourists, Integer filesizeuser, Integer imgcounttourists, Integer imgcountuser, Integer urltype, Integer isupdate) {
public UploadConfig(String suffix, Integer filesizetourists, Integer filesizeuser, Integer imgcounttourists, Integer imgcountuser, Integer urltype, Integer isupdate, Integer api) {
this.suffix = suffix;
this.filesizetourists = filesizetourists;
this.filesizeuser = filesizeuser;
@@ -20,6 +21,7 @@ public class UploadConfig {
this.imgcountuser = imgcountuser;
this.urltype = urltype;
this.isupdate = isupdate;
this.api = api;
}
public String getSuffix() {
@@ -77,4 +79,12 @@ public class UploadConfig {
public void setIsupdate(Integer isupdate) {
this.isupdate = isupdate;
}
public Integer getApi() {
return api;
}
public void setApi(Integer api) {
this.api = api;
}
}
+11
View File
@@ -1,9 +1,20 @@
package cn.hellohao.pojo;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
public class User {
private Integer id;
//@NotBlank(message = "用户名不能为空")
// @Length(min = 6, max = 20, message = "用户名需要为 6 - 20 个字符")
private String username;
//@NotBlank(message = "密码不能为空")
private String password;
// @NotBlank(message = "邮箱不能为空")
//@Email(message = "邮箱格式不正确")
private String email;
private String birthder;
private Integer level;
@@ -2,6 +2,7 @@ package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.ImgUrlUtil;
import cn.hellohao.utils.Print;
import com.netease.cloud.auth.BasicCredentials;
@@ -112,56 +113,72 @@ public class COSImageupload {
}
//初始化网易NOS对象存储
public static void Initialize(Keys k) {
public static Integer Initialize(Keys k) {
int ret = -1;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) {
// 1 初始化用户身份信息(secretId, secretKey)。
String secretId = k.getAccessKey();
String secretKey = k.getAccessSecret();
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
Region region = new Region(k.getEndpoint());
ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客户端。
cosClient = new COSClient(cred, clientConfig);
System.out.println("==="+cosClient);
//查询桶
try {
List<Bucket> buckets = cosClient.listBuckets();
for (Bucket bucket : buckets) {
if (bucket.getName().equals(k.getBucketname())) {
Print.Normal("当前桶名称:" + bucket.getName());
BarrelName = bucket.getName();
}
}
} catch (CosServiceException serverException) {
serverException.printStackTrace();
} catch (CosClientException clientException) {
clientException.printStackTrace();
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) {
// 1 初始化用户身份信息(secretId, secretKey)。
String secretId = k.getAccessKey();
String secretKey = k.getAccessSecret();
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
Region region = new Region(k.getEndpoint());
ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客户端。
cosClient = new COSClient(cred, clientConfig);
BarrelName = k.getBucketname();
//查询桶
// try {
// List<Bucket> buckets = cosClient.listBuckets();
// for (Bucket bucket : buckets) {
// if (bucket.getName().equals(k.getBucketname())) {
// Print.Normal("当前桶名称:" + bucket.getName());
// BarrelName = bucket.getName();
// }
// }
// } catch (CosServiceException serverException) {
// serverException.printStackTrace();
// } catch (CosClientException clientException) {
// clientException.printStackTrace();
// }
key = k;
ret = 1;
}
key = k;
}
return ret;
}
/**
* 客户端接口
* */
public Map<String, Integer> clientuploadCOS(Map<String, MultipartFile> fileMap, String username) throws Exception {
public Map<ReturnImage, Integer> clientuploadCOS(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) throws Exception {
File file = null;
Map<String, Integer> ImgUrl = new HashMap<>();
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
try {
// 指定要上传到 COS 上对象键
String userkey =username + "/" + uuid+times + "." + entry.getKey();
PutObjectRequest putObjectRequest = new PutObjectRequest(BarrelName, userkey, file);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
ReturnImage returnImage = new ReturnImage();
if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
// 指定要上传到 COS 上对象键
String userkey =username + "/" + uuid+times + "." + entry.getKey();
PutObjectRequest putObjectRequest = new PutObjectRequest(BarrelName, userkey, file);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + userkey);
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
// ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
}else{
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl("文件超出系统设定大小,不得超过");
ImgUrl.put(returnImage, -1);
}
} catch (Exception e) {
System.out.println("上传报错:" + e.getMessage());
}
@@ -2,6 +2,7 @@ package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.FTPUtils;
import cn.hellohao.utils.ImgUrlUtil;
import cn.hellohao.utils.Print;
@@ -100,48 +101,56 @@ public class FTPImageupload {
}
//初始化FTP对象存储
public static void Initialize(Keys k) {
public static Integer Initialize(Keys k) {
int ret = -1;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null && k.getRequestAddress()!=null ) {
FTPClient ftp = new FTPClient();
String[] host = k.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
try {
if(!ftp.isConnected()){
ftp.connect(h,p);
}
//如果是需要认证的服务器,就需要账号和密码来登录
ftp.login(k.getAccessKey(), k.getAccessSecret());
} catch (IOException e) {
e.printStackTrace();
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("") && !k.getRequestAddress().equals("") ) {
FTPClient ftp = new FTPClient();
int flag = k.getEndpoint().indexOf(":");
if(flag>0){
String[] host = k.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
try {
if(!ftp.isConnected()){
ftp.connect(h,p);
}
//如果是需要认证的服务器,就需要账号和密码来登录
ftp.login(k.getAccessKey(), k.getAccessSecret());
} catch (IOException e) {
e.printStackTrace();
}
//获取服务器返回的状态码
int reply = ftp.getReplyCode();
System.out.println(reply);
/*
* 判断是否连接成功
* 所有以2开头的代码是正完成响应。
* FTP服务器将在最终发送一个肯定的完成响应成功完成命令。
*/
if (!FTPReply.isPositiveCompletion(reply)) {
try {
ftp.disconnect();
}catch (IOException e){
System.out.println(e);
}
Print.warning("连接失败");
ret = -1;
}
Print.Normal("链接成功");
//boolean isUpload = ftp.storeFile("/ftp/upload.jpg", fis);
ftpClient1 = ftp;
key = k;
ret = 1;
}
//获取服务器返回的状态码
int reply = ftp.getReplyCode();
System.out.println(reply);
/*
* 判断是否连接成功
* 所有以2开头的代码是正完成响应。
* FTP服务器将在最终发送一个肯定的完成响应成功完成命令。
*/
if (!FTPReply.isPositiveCompletion(reply)) {
try {
ftp.disconnect();
}catch (IOException e){
System.out.println(e);
}
Print.warning("连接失败");
return;
}
Print.Normal("链接成功");
//boolean isUpload = ftp.storeFile("/ftp/upload.jpg", fis);
ftpClient1 = ftp;
key = k;
}
}
return ret;
}
/**
* 客户端接口
* */
public Map<String, Integer> clientuploadCOS(Map<String, MultipartFile> fileMap, String username) throws Exception {
public Map<ReturnImage, Integer> clientuploadFTP(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) throws Exception {
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
@@ -149,7 +158,7 @@ public class FTPImageupload {
FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret());
boolean flag = ftps.open();
File file = null;
Map<String, Integer> ImgUrl = new HashMap<>();
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
@@ -158,11 +167,22 @@ public class FTPImageupload {
String userkey =username + File.separator+ uuid+times + "." + entry.getKey();
ftps.mkDir(File.separator+username);
if (flag) {
ftps.upload(file, File.separator+userkey, "");
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey);
ImgUrl.put(key.getRequestAddress() + File.separator+userkey + username + File.separator+userkey + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
ftps.close();
if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
ftps.upload(file, File.separator+userkey, "");
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey);
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
//ImgUrl.put(key.getRequestAddress() + File.separator+userkey + username + File.separator+userkey + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
ftps.close();
}else{
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl("文件超出系统设定大小,不得超过");
ImgUrl.put(returnImage, -1);
ftps.close();
}
}
}
return ImgUrl;
@@ -2,6 +2,7 @@ package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.ImgUrlUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
@@ -81,7 +82,6 @@ public class KODOImageupload {
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
//System.out.println(putRet.hash);
new File(imgurl).delete();
} catch (QiniuException ex) {
Response r = ex.response;
@@ -112,37 +112,43 @@ public class KODOImageupload {
}
//初始化
public static void Initialize(Keys k) {
public static Integer Initialize(Keys k) {
int ret = -1;
if (k.getEndpoint() != null && k.getAccessSecret() != null && k.getEndpoint() != null
&& k.getBucketname() != null && k.getRequestAddress() != null) {
// 初始化
// 创建KODOClient实例。
Configuration cfg;
//构造一个带指定Zone对象的配置类
if (k.getEndpoint().equals("1")) {
cfg = new Configuration(Zone.zone0());
} else if (k.getEndpoint().equals("2")) {
cfg = new Configuration(Zone.zone1());
} else if (k.getEndpoint().equals("3")) {
cfg = new Configuration(Zone.zone2());
} else if (k.getEndpoint().equals("4")) {
cfg = new Configuration(Zone.zoneNa0());
} else {
cfg = new Configuration(Zone.zoneAs0());
if (!k.getEndpoint().equals("") && !k.getAccessSecret() .equals("") && !k.getEndpoint() .equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress() .equals("")) {
// 初始化
// 创建KODOClient实例。
Configuration cfg;
//构造一个带指定Zone对象的配置类
if (k.getEndpoint().equals("1")) {
cfg = new Configuration(Zone.zone0());
} else if (k.getEndpoint().equals("2")) {
cfg = new Configuration(Zone.zone1());
} else if (k.getEndpoint().equals("3")) {
cfg = new Configuration(Zone.zone2());
} else if (k.getEndpoint().equals("4")) {
cfg = new Configuration(Zone.zoneNa0());
} else {
cfg = new Configuration(Zone.zoneAs0());
}
uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(k.getAccessKey(), k.getAccessSecret());
upToken = auth.uploadToken(k.getBucketname());
key = k;
ret = 1;
}
uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(k.getAccessKey(), k.getAccessSecret());
upToken = auth.uploadToken(k.getBucketname());
key = k;
}
return ret;
}
/**
* 客户端接口
* */
public Map<String, Integer> clientuploadKODO(Map<String, MultipartFile> fileMap, String username) throws Exception {
public Map<ReturnImage, Integer> clientuploadKODO(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) throws Exception {
File file = null;
Map<String, Integer> ImgUrl = new HashMap<>();
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
@@ -151,10 +157,21 @@ public class KODOImageupload {
file = changeFile(entry.getValue());
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
try {
Response response = uploadManager.put(file,username + "/" + uuid+times + "." + entry.getKey(),upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
ReturnImage returnImage = new ReturnImage();
if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
Response response = uploadManager.put(file,username + "/" + uuid+times + "." + entry.getKey(),upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
//ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
}else{
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl("文件超出系统设定大小,不得超过");
ImgUrl.put(returnImage, -1);
}
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
@@ -8,7 +8,9 @@ import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import cn.hellohao.exception.StorageSourceInitException;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.ImgUrlUtil;
import cn.hellohao.utils.Print;
import com.netease.cloud.services.nos.model.ObjectMetadata;
@@ -50,15 +52,12 @@ public class NOSImageupload {
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
try {
nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), file);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
} catch (Exception e) {
System.out.println("上传报错:" + e.getMessage());
}
nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), file);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
}
return ImgUrl;
}else{
@@ -82,7 +81,7 @@ public class NOSImageupload {
}else if(entry.getKey().equals("gif")){
head = "image/gif";
}else{
System.err.println("位置格式文件,无法定义header头。");
System.err.println("未知格式文件,无法定义header头。");
}
meta.setHeader("Content-Type", head);//image/jpeg
File file = new File(imgurl);
@@ -126,53 +125,71 @@ public class NOSImageupload {
//初始化网易NOS对象存储
public static void Initialize(Keys k) {
public static Integer Initialize(Keys k) {
int ret = -1;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ){
// 初始化
Credentials credentials = new BasicCredentials(k.getAccessKey(), k.getAccessSecret());
nosClient = new NosClient(credentials);
nosClient.setEndpoint(k.getEndpoint());
// 初始化TransferManager
TransferManager transferManager = new TransferManager(nosClient);
// 列举桶
ArrayList bucketList = new ArrayList();
for (Bucket bucket : nosClient.listBuckets()) {
bucketList.add(bucket.getName());
}
for (Object object : bucketList) {
if (object.toString().equals(k.getBucketname())) {
BarrelName = object.toString();
}
}
key = k;
}
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ){
// 初始化
Credentials credentials = new BasicCredentials(k.getAccessKey(), k.getAccessSecret());
nosClient = new NosClient(credentials);
nosClient.setEndpoint(k.getEndpoint());
// 列举桶
ArrayList bucketList = new ArrayList();
//加入传入的key值不正确,这里会报异常,页面500,如何捕捉异常处理。
BarrelName = k.getBucketname();
// for (Bucket bucket : nosClient.listBuckets()) {
// bucketList.add(bucket.getName());
// }
// for (Object object : bucketList) {
// if (object.toString().equals(k.getBucketname())) {
// BarrelName = object.toString();
// }
// }
key = k;
ret = 1;
}else{
ret = -1;
}
}else{
ret = -1;
//throw new StorageSourceInitException("当前数据源配置不完整,请管理员前往后台配置。");
}
return ret;
}
/**
* 客户端接口
* */
public Map<String, Integer> clientuploadNOS(Map<String, MultipartFile> fileMap, String username) throws Exception {
public Map<ReturnImage, Integer> clientuploadNOS(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) throws Exception {
File file = null;
Map<String, Integer> ImgUrl = new HashMap<>();
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
try {
nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), file);
ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
Print.warning(entry.getValue().getSize());
ReturnImage returnImage = new ReturnImage();
if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), file);
//ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
}else{
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl("文件超出系统设定大小,不得超过");
ImgUrl.put(returnImage, -1);
}
} catch (Exception e) {
System.out.println("上传报错:" + e.getMessage());
}
}
return ImgUrl;
}
}
@@ -2,6 +2,7 @@ package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.ImgUrlUtil;
import cn.hellohao.utils.Print;
import com.aliyun.oss.OSSClient;
@@ -113,24 +114,28 @@ public class OSSImageupload {
}
//初始化
public static void Initialize(Keys k) {
public static Integer Initialize(Keys k) {
int ret = -1;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) {
// 初始化
// 创建OSSClient实例。
ossClient = new OSSClient(k.getEndpoint(), k.getAccessKey(), k.getAccessSecret());
key = k;
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) {
ossClient = new OSSClient(k.getEndpoint(), k.getAccessKey(), k.getAccessSecret());
key = k;
ret=1;
}
}
return ret;
}
/**
* 客户端接口
* */
public Map<String, Integer> clientuploadOSS(Map<String, MultipartFile> fileMap, String username) throws Exception {
public Map<ReturnImage, Integer> clientuploadOSS(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) throws Exception {
File file = null;
Map<String, Integer> ImgUrl = new HashMap<>();
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
//设置Header
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
@@ -153,14 +158,21 @@ public class OSSImageupload {
System.err.println("位置格式文件,无法定义header头。");
}
meta.setHeader("Content-Type", head);//image/jpeg
// 上传文件流。
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
ossClient.putObject(key.getBucketname(), username + "/" + uuid+times + "." + entry.getKey(),file,meta);
// 关闭OSSClient。
//ossClient.shutdown();
Print.Normal(entry.getValue().getSize());
ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()/1024));
ReturnImage returnImage = new ReturnImage();
if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
// 上传文件流。
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
ossClient.putObject(key.getBucketname(), username + "/" + uuid+times + "." + entry.getKey(),file,meta);
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
//ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()/1024));
}else{
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl("文件超出系统设定大小,不得超过");
ImgUrl.put(returnImage, -1);
}
}
return ImgUrl;
@@ -2,6 +2,7 @@ package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.ImgUrlUtil;
import com.UpYun;
import com.aliyun.oss.OSSClient;
@@ -91,23 +92,29 @@ public class USSImageupload {
}
//初始化
public static void Initialize(Keys k) {
public static Integer Initialize(Keys k) {
int ret = -1;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) {
// 初始化
// 创建UpYun实例。
upyun = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret());
key = k;
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) {
// 初始化
// 创建UpYun实例。
upyun = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret());
key = k;
ret = 1;
}
}
return ret;
}
/**
* 客户端接口
* */
public Map<String, Integer> clientuploadUSS(Map<String, MultipartFile> fileMap, String username) throws Exception {
public Map<ReturnImage, Integer> clientuploadUSS(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) throws Exception {
File file = null;
Map<String, Integer> ImgUrl = new HashMap<>();
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
//设置Header
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
@@ -118,13 +125,24 @@ public class USSImageupload {
file = changeFile(entry.getValue());
// 上传文件流。
System.out.println("客户端:待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
// 例2:采用数据流模式上传文件(节省内存),自动创建父级目录
upyun.setContentMD5(UpYun.md5(file));
boolean result = upyun.writeFile(username + "/" + uuid+times + "." + entry.getKey(), file, true);
if(result){
ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
ReturnImage returnImage = new ReturnImage();
if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
// 例2:采用数据流模式上传文件(节省内存),自动创建父级目录
upyun.setContentMD5(UpYun.md5(file));
boolean result = upyun.writeFile(username + "/" + uuid+times + "." + entry.getKey(), file, true);
if(result){
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
//ImgUrl.put(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
}else{
System.err.println("上传失败");
}
}else{
System.err.println("上传失败");
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl("文件超出系统设定大小,不得超过");
ImgUrl.put(returnImage, -1);
}
}
return ImgUrl;
+3 -15
View File
@@ -11,22 +11,10 @@ public class test1 {
public static void main(String[] args) {
//匿名登录(无需帐号密码的FTP服务器)
Ftp ftp = new Ftp("hellohao.cn");
ftp.init("hellohao.cn",21,"test","test");
//进入远程目录
//ftp.cd("/opt/upload");
//上传本地文件
ftp.upload("/ftp/222222222.jpg", FileUtil.file("C:\\Users\\tiansh\\Desktop\\11.jpg"));
//下载远程文件
//ftp.download("/opt/upload", "test.jpg", FileUtil.file("e:/test2.jpg"));
//关闭连接
try {
ftp.close();
} catch (IOException e) {
e.printStackTrace();
}
String str = "hellohao.cn:888";
int flag = str.indexOf(":");
System.out.println(flag);
}
@@ -1,6 +1,7 @@
package cn.hellohao.utils;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import com.google.gson.Gson;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@@ -78,10 +79,10 @@ public class LocUpdateImg {
/**
* 客户端接口
* */
public Map<String, Integer> clientuploadKODO(Map<String, MultipartFile> fileMap, String username) throws Exception {
public static Map<ReturnImage, Integer> clientuploadFTP(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) {
String filePath =File.separator + "HellohaoData" + File.separator;
File file = null;
Map<String, Integer> ImgUrl = new HashMap<>();
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
@@ -89,16 +90,27 @@ public class LocUpdateImg {
//file = SetFiles.changeFile(entry.getValue());
// 上传文件流。
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
File dest = new File(filePath + username + File.separator+ uuid+times + "." + entry.getKey());
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
entry.getValue().transferTo(dest);
ImgUrl.put(username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
} catch (IOException e) {
e.printStackTrace();
System.err.println("上传失败");
ReturnImage returnImage = new ReturnImage();
if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
File dest = new File(filePath + username + File.separator+ uuid+times + "." + entry.getKey());
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
entry.getValue().transferTo(dest);
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
//ImgUrl.put(username + "/" + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
} catch (IOException e) {
e.printStackTrace();
System.err.println("上传失败");
}
}else{
//ImgUrl.put("文件超出系统设定大小,不得超过"+uploadConfig.getFilesizeuser()+"M", -1);
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl("文件超出系统设定大小,不得超过");
ImgUrl.put(returnImage,-1);
}
}
return ImgUrl;