上传客户端
这是所需要的jar包(httpclient可能会因为版本的问题而导致有些类没有,建议尝试多个版本)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
<scope>compile</scope>
</dependency>
获取路径下的所有的文件,根据业务逻辑的需要进行文件的重命名操作
public Map<String, Object> HttpPostWithJson(String date) {
if (null != date){
if(date==curDateStr){
repairmark = "1";
}else{
repairmark = "0";
}
}
Map<String, Object> returnMap = null;
String FileUploadPath = FilePath;
//完整路径(拼接用户名和密码)
String loadURL = FileUploadUrl+"?USER="+user+"&PASSWORD="+password;
//拿到这个文件
File file = new File(FileUploadPath);
//获取这个目录下面所有的文件
String[] tempList = file.list();
if(null != tempList){
for (int i = 0; i < tempList.length; i++) {
//判断如果不是当天,则将文件重命名
if ("0".equals(repairmark)){
String uuidStr = getUuidStr();
String path = tempList[i].substring(0,tempList[i].lastIndexOf("_"));
String rename = path+"_"+uuidStr+tempList[i].substring(tempList[i].lastIndexOf("."));
try {
temp = this.renameFile(FileUploadPath,tempList[i],rename);
} catch (Exception e) {
e.printStackTrace();
}
}else{
temp = new File(FileUploadPath+"/"+tempList[i]);
}
returnMap = this.fileUpload(temp,loadURL);
}
}
//处理返回值
return returnMap;
}
获取文件并开始传输文件
public Map<String,Object> fileUpload(File temp,String loadURL){
Map<String, Object> returnMap = null;
try {
httpClient = HttpClients.createDefault();
//创建连接
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
HttpPost httpPost = new HttpPost(loadURL);
FileBody bin = new FileBody(temp);
multipartEntityBuilder.addPart("file",bin);
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
response = httpClient.execute(httpPost);
//判断请求是否成功(200为成功,其他返回code请参考http返回code)
if (response.getStatusLine().getStatusCode() == 200 ){
HttpEntity resEntity = response.getEntity();
if(resEntity !=null){
returnMap = toJson(EntityUtils.toString(resEntity));
}
}
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
try {
logger.info("请求完成,连接关闭");
httpClient.close();
response.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
return returnMap;
}
文件的重命名
/**文件重命名
* @param path 文件目录
* @param oldname 原来的文件名
* @param newname 新文件名
*/
public File renameFile(String path,String oldname,String newname)throws Exception{
File newfile = null;
if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
File oldfile=new File(path+"/"+oldname);
newfile=new File(path+"/"+newname);
if(!oldfile.exists()){
logger.info("需要重命名的文件不存在");
return null;
}
if(newfile.exists())
logger.info(newname+"已经存在!");
else{
oldfile.renameTo(newfile);
logger.info("重命名完成"+newfile);
}
}else{
logger.info("新文件名和旧文件名相同...");
}
return newfile;
}
获取文件传输完成的返回值并开始解析
//用fastjson解析返回的数据
private Map<String,Object> toJson(String jsonArray){
Map<String,Object> map = new HashMap<String, Object>();
try {
logger.info("开始解析返回的数据------");
jsonStr = JSONObject.parseObject(jsonArray);
String serviceFlag = (String) jsonStr.get("serviceFlag");
String msg = (String) jsonStr.get("msg");
map.put("serviceFlag",serviceFlag);
map.put("msg",msg);
}catch (Exception e){
logger.info("解析JSON出错,数据结构不对");
} finally {
logger.info("返回的JSON为:"+jsonStr);
logger.info("JSON数据解析完成---------");
}
return map;
}
完整的代码
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* The type File upload.
*/
@Service("fileUploadImplService")
public class FileUploadImpl {
/**
* The Logger.
*/
Logger logger = Logger.getLogger(FileUploadImpl.class);
/**
* The Response.
*/
CloseableHttpResponse response;
String curDateStr = dateToStr(new Date());
//文件路径
String FilePath = "";
//上传路径
String FileUploadUrl = "";
//此字段个人业务逻辑的需要
String repairmark = "1";
//用户名
String user = "";
//密码
String password = "";
private JSONObject jsonStr;
private CloseableHttpClient httpClient;
private File temp;
public Map<String, Object> HttpPostWithJson(String date) {
if (null != date) {
if (date == curDateStr) {
repairmark = "1";
} else {
repairmark = "0";
}
}
Map<String, Object> returnMap = null;
String FileUploadPath = FilePath;
//完整路径(拼接用户名和密码)
String loadURL = FileUploadUrl + "?USER=" + user + "&PASSWORD=" + password;
//拿到这个文件
File file = new File(FileUploadPath);
//获取这个目录下面所有的文件
String[] tempList = file.list();
if (null != tempList) {
for (int i = 0; i < tempList.length; i++) {
//判断如果不是当天,则将文件重命名
if ("0".equals(repairmark)) {
String uuidStr = getUuidStr();
String path = tempList[i].substring(0, tempList[i].lastIndexOf("_"));
String rename = path + "_" + uuidStr + tempList[i].substring(tempList[i].lastIndexOf("."));
try {
temp = this.renameFile(FileUploadPath, tempList[i], rename);
} catch (Exception e) {
e.printStackTrace();
}
} else {
temp = new File(FileUploadPath + "/" + tempList[i]);
}
returnMap = this.fileUpload(temp, loadURL);
}
}
//处理返回值
return returnMap;
}
public Map<String, Object> fileUpload(File temp, String loadURL) {
Map<String, Object> returnMap = null;
try {
httpClient = HttpClients.createDefault();
//创建连接
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
HttpPost httpPost = new HttpPost(loadURL);
FileBody bin = new FileBody(temp);
multipartEntityBuilder.addPart("file", bin);
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
response = httpClient.execute(httpPost);
//判断请求是否成功(200为成功,其他返回code请参考http返回code)
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {/**文件重命名
* @param path 文件目录
* @param oldname 原来的文件名
* @param newname 新文件名
*/
public File renameFile (String path, String oldname, String newname)throws Exception {
File newfile = null;
if (!oldname.equals(newname)) {//新的文件名和以前文件名不同时,才有必要进行重命名
File oldfile = new File(path + "/" + oldname);
newfile = new File(path + "/" + newname);
if (!oldfile.exists()) {
logger.info("需要重命名的文件不存在");
return null;
}
if (newfile.exists())
logger.info(newname + "已经存在!");
else {
oldfile.renameTo(newfile);
logger.info("重命名完成" + newfile);
}
} else {
logger.info("新文件名和旧文件名相同...");
}
return newfile;
}
returnMap = toJson(EntityUtils.toString(resEntity));
}
}
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
try {
logger.info("请求完成,连接关闭");
httpClient.close();
response.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
return returnMap;
}
//用fastjson解析返回的数据
private Map<String, Object> toJson(String jsonArray) {
Map<String, Object> map = new HashMap<String, Object>();
try {
logger.info("开始解析返回的数据------");
jsonStr = JSONObject.parseObject(jsonArray);
String serviceFlag = (String) jsonStr.get("serviceFlag");
String msg = (String) jsonStr.get("msg");
map.put("serviceFlag", serviceFlag);
map.put("msg", msg);
} catch (Exception e) {
logger.info("解析JSON出错,数据结构不对");
} finally {
logger.info("返回的JSON为:" + jsonStr);
logger.info("JSON数据解析完成---------");
}
return map;
}
//创建一个UUID 避免文件名字重复
public static String getUuidStr() {
String uuidStr = null;
UUID uuid = UUID.randomUUID();
uuidStr = uuid.toString();
uuidStr = uuidStr.replace("-", "");
return uuidStr;
}
//获取当前的时间
public static String dateToStr(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dateStr = sdf.format(date);
return dateStr;
}
}
文件上传服务端
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;
public class UploadFile {
//日志记录
private static final Logger logger = Logger.getLogger(UploadFile.class);
public static String dateToStr(Date date){
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
String dateStr=sdf.format(date);
return dateStr;
}
public static String getUuidStr(){
String uuidStr=null;
UUID uuid=UUID.randomUUID();
uuidStr=uuid.toString();
uuidStr=uuidStr.replace("-", "");
return uuidStr;
}
public static String getcurTime(){
String curTime=null;
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
curTime=sdf.format(new Date());
return curTime;
}
public void FileUploadService(HttpServletRequest request, HttpServletResponse response) {
//设置默认的用户名和密码
String GloUser = "";
String GloPwd = "";
//设置一段统一的标识
String ceairSocialCreditCode = "";
String curDateStr= dateToStr(new Date());
//文件地址
String FilePath ="";
String uip = getIPAddress(request);
try {
String user = request.getParameter("USER");
String pwd = request.getParameter("PASSWORD");
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
.getServletContext());
if (GloUser.equals(user)&&GloPwd.equals(pwd)){
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
MultipartHttpServletRequest multiRequest = resolver.resolveMultipart(request);
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上传文件
MultipartFile multipartFile = multiRequest.getFile(iter.next());
if (multipartFile != null) {
String fileName = multipartFile.getOriginalFilename();
if (fileName.trim() != null && fileName.trim().length() > 0) {
CommonsMultipartFile cf = (CommonsMultipartFile) multipartFile;
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
File tempFile = fi.getStoreLocation();
String name = tempFile.getName();
// 拿到文件,并开始重命名存储
String dateStr= getcurTime();
String strdate = curDateStr+name.substring(name.lastIndexOf("."));
String uuidStr = getUuidStr();
String fileSaveName = ceairSocialCreditCode+"_"+name.substring(0,name.length()-strdate.length())+dateStr+"_"+uuidStr+name.substring(name.lastIndexOf("."));
String path = name.substring(0,name.lastIndexOf("_"));
String characteristic = path.substring(0,path.lastIndexOf("_"));
String filePath = FilePath+"//"+characteristic+"//"+curDateStr+"//"+fileSaveName;
File filesavePath = new File(filePath);
filesavePath.mkdirs();
logger.info("创建文件:"+filePath);
logger.info("文件原名字为:"+name);
multipartFile.transferTo(new File(filePath));
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{'serviceFlag':'1','MSG':'文件上传成功'}");
}
}
}
}
}else{
logger.info("非法入侵!账号:"+user+";密码:"+pwd+";ip:"+uip);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{'serviceFlag':'0','MSG':'警告:用户名与密码不正确!!!'}");
}
}catch (Exception e){
logger.error(e.getMessage());
}
}
/**
* @param request
* @return
*/
private static String getIPAddress(HttpServletRequest request) {
String ip = null;
//X-Forwarded-For:Squid 服务代理
String ipAddresses = request.getHeader("X-Forwarded-For");
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//Proxy-Client-IP:apache 服务代理
ipAddresses = request.getHeader("Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//WL-Proxy-Client-IP:weblogic 服务代理
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//HTTP_CLIENT_IP:有些代理服务器
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//X-Real-IP:nginx服务代理
ipAddresses = request.getHeader("X-Real-IP");
}
//有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
if (ipAddresses != null && ipAddresses.length() != 0) {
ip = ipAddresses.split(",")[0];
}
//还是不能获取到,最后再通过request.getRemoteAddr();获取
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
文件下载地址:
https://mp.youkuaiyun.com/postedit/85158060
阿里云新老客户专属低价&高额代金券新用户低至1折云服务器低至89元年
https://www.aliyun.com/minisite/goods?userCode=b84d0jpg