需求:一个项目上传的附件存在另一个项目的数据库中;
分析:可以在第一个项目将附件上传存好后,直接调用另一个项目的数据库(使用多数据源),将上传的路径写入保存即可。但是,这样在另一个项目中,预览此附件会找不到路径,因为两个项目预览拼接的路径不一样导致预览失败。这里用另一个方法,先将附件上传后调用另一个项目保存附件的接口保存附件,成功后,再将之前上传的附件删除,这样就不会占用空间。
代码:
// 首先调用此接口上传附件
@PostMapping(value = "/upload")
public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
Result<?> result = new Result<>();
String savePath = "";
String bizPath = request.getParameter("biz");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
if(oConvertUtils.isEmpty(bizPath)){
if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
//未指定目录,则用阿里云默认目录 upload
bizPath = "upload";
//result.setMessage("使用阿里云文件上传时,必须添加目录!");
//result.setSuccess(false);
//return result;
}else{
bizPath = "";
}
}
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
//update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
savePath = this.uploadLocal(file,bizPath);
//update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
/** 富文本编辑器及markdown本地上传时,采用返回链接方式
//针对jeditor编辑器如何使 lcaol模式,采用 base64格式存储
String jeditor = request.getParameter("jeditor");
if(oConvertUtils.isNotEmpty(jeditor)){
result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
result.setSuccess(true);
return result;
}else{
savePath = this.uploadLocal(file,bizPath);
}
*/
}else{
//update-begin-author:taoyan date:20200814 for:文件上传改造
savePath = CommonUtils.upload(file, bizPath, uploadType);
//update-end-author:taoyan date:20200814 for:文件上传改造
}
if(oConvertUtils.isNotEmpty(savePath)){
result.setMessage(savePath);
result.setSuccess(true);
}else {
result.setMessage("上传失败!");
result.setSuccess(false);
}
return result;
}
//附件上传后调用此接口请求另一个项目
@PostMapping(value = "/uploadFile")
public Result<?> uploadFile(@RequestBody String jsonStr, HttpServletRequest request, HttpServletResponse response) {
Result<?> result = new Result<>();
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
JSONObject jsonObj = JSONObject.parseObject(jsonStr);
String orderId = jsonObj.get("orderId").toString();
JSONArray json = JSONArray.parseArray(jsonObj.get("fileList").toString());
String resultVal = "上传失败";
RequestBaseUrl info = requestBaseUrlService.getInfo();
//另一个接口
String actionUrl = info.getUrl3() + "/predictOrderController.do?fileReceive&orderno=" + orderId;
Map<String, File> files = new HashMap<String, File>();
for (Object o : json) {
Map map = (Map)o;
//附件已保存路径
String filePath = uploadpath + File.separator + map.get("filePath").toString();
File file = new File(filePath);
//判断是否有此附件
if(!file.exists()){
response.setStatus(404);
result.setMessage("保存失败");
result.setSuccess(false);
throw new RuntimeException("文件不存在..");
} else {
files.put(file.getName(), file);
}
}
try {
//调用将附件传输给另一个附件的方法
resultVal = upLoadFilePost(actionUrl, files);
String actionLog = "添加附件: 上传成功";
if("true".equals(resultVal)) {
resultVal = "上传成功,请到编辑中查看!";
for (Object o : json) {
Map map = (Map)o;
String filePath = uploadpath + File.separator + map.get("filePath").toString();
File file = new File(filePath);
file.delete();
}
} else {
actionLog = "添加附件: 上传失败";
result.setSuccess(false);
}
Date date = new Date();
BusinessActionlog businessActionlog = new BusinessActionlog();
businessActionlog.setCreateBy(sysUser.getUsername());
businessActionlog.setCreateName(sysUser.getRealname());
businessActionlog.setActionlogType("EXPRESS");
businessActionlog.setActionlogCreatedate(date);
businessActionlog.setCreateDate(date);
businessActionlog.setActionlogBusinesscode(orderId);
businessActionlog.setActionlogContent(actionLog);
predictOrderService.saveActionLog(businessActionlog);
} catch (Exception e) {
e.printStackTrace();
}
result.setMessage(resultVal);
return result;
}
//将附件传输给另一个项目并得到返回结果
public String upLoadFilePost(String actionUrl, Map<String, File> files) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(15 * 1000);
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false);
conn.setRequestMethod("POST"); // Post方式
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY);
DataOutputStream outStream = new DataOutputStream(
conn.getOutputStream());
// 发送文件数据
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
if (res == 200) {
InputStream in = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(isReader);
String line = "";
String data = "";
while ((line = bufReader.readLine()) != null) {
data += line;
}
outStream.close();
conn.disconnect();
return data;
}
outStream.close();
conn.disconnect();
return null;
}