demo思路:
1、定义上传 文件名称 。(此demo目前对文件大小无逻辑处理与限制。)
2、明确上传到指定的服务器路径。
3、将文件先上传到本地。
4、再从本地上传到指定服务器。
5、为了节省资源,最终不论文件有无上传成功都应需删除本地文件。
当前为了测试,该demo不分层处理,全在controller层。
具体代码如下:
package com.fin.kpl.admin.controller.common.file;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.*;
/**
* 上传图片文件到服务器
*/
@Controller
public class FileDemo {
public final static Logger log = LoggerFactory.getLogger(FileDemo.class);
@Value("${spring.targetAddress =10.01.111.90}")
private String targetAddress;
@RequestMapping(value = "/adm/commons/file/uploadFileDemo")
public @ResponseBody
Demo uploadFileDemo(
@RequestParam(value = "photoBase64") String photoBase64,
HttpServletRequest request,
HttpServletResponse response, ModelMap modelMap) {
// 文件上传到服务器 目前文件大小暂不测。
//1、定义上传 文件名称
//2、明确上传到指定的服务器路径
//3、上传到本地
//4、从本地上传到指定服务器
//5、删除本地文件
//为了测试,该demo不分层。
return uploadFileDemo(photoBase64);
}
// 上传文件
private Demo uploadFileDemo(String photoBase64) {
Demo demo = new Demo();
log.info("入参--------------{}", JSON.toJSONString(photoBase64));
//创建上传到服务器的文件名称。
String uuid = UUID.randomUUID().toString().replace("-", "");
String fileName = LocalDate.now().toString() + uuid;
//获取上传文件的类型
String[] split = photoBase64.split(",");
String fileType = split[0].split("/")[1].split(";")[0];
String base64 = split[1];
//文件路径
String pathLocal = "/demo/demo/data";
//上传到服务器的项目文件路径 ---->需要确认,不可随便上传到一个路径
// (当前路径为了测试,是自定义。)
String pathServer = "/data" + fileName + fileType;//源文件路径
log.info("上传到服务器文件路径--------{}", pathServer);
//将需要上传的文件保存到本地
boolean bo = saveLocal(base64, pathLocal, fileType, fileName);
try {
//将本地文件上传到指定服务器
demo = saveServer(pathServer, fileName, fileType);
return demo;
} catch (Exception e) {
log.error("上传失败---------{}", e);
demo.setCode("999999");
demo.setMsg("false");
} finally {
File file = new File(pathServer);
if (file.exists()) {
file.delete();//删除本地临时文件。
log.info("删除本地文件---------{}", pathServer);
}
}
return demo;
}
//将本地文件上传到指定服务器
private Demo saveServer(String pathServer, String fileName, String fileType) throws InterruptedException, ExecutionException {
//目标指定文件服务器路径 填服务器home下路径,这里是测试路径(自定义)。
//项目中可以在配置文件中配置
String tPath = "/server/file/data";
//线程池
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(8, 16, 1000,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(10)
, new ThreadPoolExecutor.AbortPolicy());
// 两种方式 多数 单一
String[] data = {"123", "789"};
CountDownLatch countDownLatch = new CountDownLatch(data.length);
List<Future<Demo>> list = new ArrayList<>();
for (String d : data) {
//项目中可以在配置文件中配置
String targetPath = tPath + d + fileName + "." + fileType;
list.add(poolExecutor.submit(() -> {
countDownLatch.countDown();
;
Demo demo = uploadTo(targetPath, pathServer);
return demo;
}));
}
// //单一
// //上传到服务器的文件夹标识
// String s = "S"+ String.valueOf(System.currentTimeMillis());
// poolExecutor.submit(() -> {
// countDownLatch.countDown();
// ;
// Demo demo1 = uploadTo(s, pathServer);
// return demo1;
// });
Demo demo = null;
countDownLatch.await();
for (int i = 0; i < list.size(); i++) {
Future<Demo> demoFuture = list.get(i);
if (!demoFuture.isCancelled()) {
demo = demoFuture.get();
if (!"000000".equals(demo.getCode())) {
return demo;
}
}
}
poolExecutor.shutdown();
return demo;
}
//Http 请求
private Demo uploadTo(String targetPath, String pathServer) {
Demo demo = new Demo();
try {
Request request = new Request();
//获取服务器IP
String ipAddr = getServerIpAddr();
//服务器IP = 服务器 +IP+端口号
String ipServer = "demo@" + ipAddr + ":8080";
log.info("获取服务器地址:{}" + ipServer);
//设置源端ip
request.setConsumerSvrId(ipServer);
//设置源文件端路径
request.setSrcFilePath(pathServer);
//设置目的端ip
request.setDestSvrId(targetAddress);
//设置目的端路径
request.setDesFilePath(targetPath);
//coed 自定义
request.setTranCode("demo");
//
log.info("设置目的端ip---------{}", targetAddress);
log.info("设置源文件端路径---------{}", pathServer);
//发送请求
String url = "http://xx.xx.xxx.xx:9090/demo";//服务器请求路径
demo = sentHttpFile(url, request);
} catch (Exception e) {
log.error("文件上传到服务器异常------------{}", e);
}
return demo;
}
private Demo sentHttpFile(String url, Request request) throws IOException {
HttpURLConnection conn = null;
BufferedReader in = null;
OutputStreamWriter out = null;
String respMsg = "";
Demo demo = new Demo();
try {
conn = (HttpURLConnection) (new java.net.URL(url)).openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.connect();
try {
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
String paramStr = request.toHttpParamStr();
out.write(paramStr);
out.flush();
String line ;
for(in =new BufferedReader(new InputStreamReader(conn.getInputStream()));
(line=in.readLine())!=null;respMsg = respMsg +line){}
String[] split = respMsg.split("\"");
demo.setCode(split[3]);
demo.setMsg(split[7]);
demo.setSerialNumber(split[11]);
Demo demo1 = demo;
return demo1;
} finally {
if (null != out) {
out.close();
}
if (null != in) {
in.close();
}
}
} catch (ProtocolException p) {
throw p;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
//获取服务器IP
private String getServerIpAddr() {
String ip = null;
try {
Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
for (; enumeration.hasMoreElements(); ) {
NetworkInterface en = (NetworkInterface) enumeration.nextElement();
Enumeration ion = en.getInetAddresses();
for (; ion.hasMoreElements(); ) {
InetAddress ia = (InetAddress) ion.nextElement();
if (ia instanceof Inet4Address &&
//本地地址
!ia.getHostAddress().equals("127.0.0.1")
//项目服务地址如 "111:90" 测试编写
&& !ia.getHostAddress().contains("111:90")) {
ip = ia.getHostAddress();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ip;
}
//将需要上传的文件转成图片的形式保存到本地
private boolean saveLocal(String base64, String path, String fileType, String fileName) {
boolean bo = false;
OutputStream outputStream = null;
//转图片
BASE64Decoder base64Decoder = new BASE64Decoder();
String dataPath = path + fileName + fileType;
try {
log.info("生成图片,保存到本地路径---------{}", dataPath);
File imgFile = new File(dataPath);
if (!imgFile.getParentFile().exists()) {
imgFile.getParentFile().mkdirs();
}
outputStream = new FileOutputStream(dataPath);
//
byte[] bytes = base64Decoder.decodeBuffer(base64);
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
outputStream.write(bytes);
bo = true;
log.info("文件图片保存本地------成功!");
} catch (Exception e) {
log.error("文件图片保存本地失败--------{}", e);
} finally {
if (null != outputStream) {
try {
outputStream.flush();
outputStream.close();
} catch (Exception e) {
log.error("文件图片保存本地失败--------{}", e);
}
}
}
return bo;
}
}
package com.fin.kpl.admin.controller.common.file;
import org.apache.commons.compress.utils.Lists;
import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class Demo {
private String code ; //"000000" 为成功
private String msg;
private String serialNumber;
private Map<String, Object> data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
}
package com.fin.kpl.admin.controller.common.file;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Request implements Serializable {
public static final String SYNC_TRANSFER = "0";
public static final String ASYNC_TRANSFER = "1";
private String ConsumerId;
private String TranDate;
private String TranTime;
private String ConsumerSeqNo;
private String FileFlag;
private String ConsumerSvrId;
private String DestSvrId;
private String SrcFilePath;
private String DesFilePath;
private String TranCode;
private String ParmInf;
private String CrtFlg;
private String PolgFlg;
public static String getSyncTransfer() {
return SYNC_TRANSFER;
}
public static String getAsyncTransfer() {
return ASYNC_TRANSFER;
}
public String getConsumerId() {
return ConsumerId;
}
public void setConsumerId(String consumerId) {
ConsumerId = consumerId;
}
public String getTranDate() {
return TranDate;
}
public void setTranDate(String tranDate) {
TranDate = tranDate;
}
public String getTranTime() {
return TranTime;
}
public void setTranTime(String tranTime) {
TranTime = tranTime;
}
public String getConsumerSeqNo() {
return ConsumerSeqNo;
}
public void setConsumerSeqNo(String consumerSeqNo) {
ConsumerSeqNo = consumerSeqNo;
}
public String getFileFlag() {
return FileFlag;
}
public void setFileFlag(String fileFlag) {
FileFlag = fileFlag;
}
public String getConsumerSvrId() {
return ConsumerSvrId;
}
public void setConsumerSvrId(String consumerSvrId) {
ConsumerSvrId = consumerSvrId;
}
public String getDestSvrId() {
return DestSvrId;
}
public void setDestSvrId(String destSvrId) {
DestSvrId = destSvrId;
}
public String getSrcFilePath() {
return SrcFilePath;
}
public void setSrcFilePath(String srcFilePath) {
SrcFilePath = srcFilePath;
}
public String getDesFilePath() {
return DesFilePath;
}
public void setDesFilePath(String desFilePath) {
DesFilePath = desFilePath;
}
public String getTranCode() {
return TranCode;
}
public void setTranCode(String tranCode) {
TranCode = tranCode;
}
public String getParmInf() {
return ParmInf;
}
public void setParmInf(String parmInf) {
ParmInf = parmInf;
}
public String getCrtFlg() {
return CrtFlg;
}
public void setCrtFlg(String crtFlg) {
CrtFlg = crtFlg;
}
public String getPolgFlg() {
return PolgFlg;
}
public void setPolgFlg(String polgFlg) {
PolgFlg = polgFlg;
}
@Override
public String toString() {
return "Request{" +
"ConsumerId='" + ConsumerId + '\'' +
", TranDate='" + TranDate + '\'' +
", TranTime='" + TranTime + '\'' +
", ConsumerSeqNo='" + ConsumerSeqNo + '\'' +
", FileFlag='" + FileFlag + '\'' +
", ConsumerSvrId='" + ConsumerSvrId + '\'' +
", DestSvrId='" + DestSvrId + '\'' +
", SrcFilePath='" + SrcFilePath + '\'' +
", DesFilePath='" + DesFilePath + '\'' +
", TranCode='" + TranCode + '\'' +
", ParmInf='" + ParmInf + '\'' +
", CrtFlg='" + CrtFlg + '\'' +
", PolgFlg='" + PolgFlg + '\'' +
'}';
}
public String toHttpParamStr() throws UnsupportedEncodingException {
String charWord = "&";
StringBuffer sb = new StringBuffer();
if (this.ConsumerId != null) {
sb.append("consumerId=" + URLEncoder.encode(this.ConsumerId, "UTF-8") + charWord);
}
if (this.TranDate != null) {
sb.append("tranDate=" + URLEncoder.encode(this.TranDate, "UTF-8") + charWord);
}
if (this.TranTime != null) {
sb.append("tranTime=" + URLEncoder.encode(this.TranTime, "UTF-8") + charWord);
}
if (this.ConsumerSeqNo != null) {
sb.append("consumerSeqNo=" + URLEncoder.encode(this.ConsumerSeqNo, "UTF-8") + charWord);
}
if (this.TranCode != null) {
sb.append("tranCode=" + URLEncoder.encode(this.TranCode, "UTF-8") + charWord);
}
if (this.ParmInf != null) {
sb.append("parmInf=" + URLEncoder.encode(this.ParmInf, "UTF-8") + charWord);
}
if (this.CrtFlg != null) {
sb.append("crtFlg=" + URLEncoder.encode(this.CrtFlg, "UTF-8") + charWord);
}
if (this.PolgFlg != null) {
sb.append("polgFlg=" + URLEncoder.encode(this.PolgFlg, "UTF-8") + charWord);
}
if ("1".equals(this.FileFlag)) {
sb.append("async=1&");
} else {
sb.append("async=0&");
}
if (this.ConsumerSvrId != null) {
sb.append("consumerSvrId=" + URLEncoder.encode(this.ConsumerSvrId, "UTF-8") + charWord);
}
if (this.DestSvrId != null) {
sb.append("destSvrId=" + URLEncoder.encode(this.DestSvrId, "UTF-8") + charWord);
}
if (this.SrcFilePath != null) {
sb.append("srcFilePath=" + URLEncoder.encode(this.SrcFilePath, "UTF-8") + charWord);
}
if (this.DesFilePath != null) {
sb.append("desFilePath=" + URLEncoder.encode(this.DesFilePath, "UTF-8") + charWord);
}
return sb.toString();
}
}
谢谢!