上传工具类
/**
* 上传工具类
*
* @ClassName: UpfileUtils
* @author: Amy
* @date: 2020年8月5日 上午11:44:04
* @Copyright:
*/
public class UpfileUtils {
/**
* 上传
* @Title: upload
* @param: @param request
* @param: @param path
* @param: @param uptype
* @param: @return
* @return: String
* @throws
*/
public static String upload(HttpServletRequest request,String path,String uptype){
Map<String, String> modelMap = new HashMap<>();
try {
MultipartHttpServletRequest rq = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> file_list = rq.getFileMap();
if (file_list != null && file_list.size() > 0) {
if (file_list.containsKey("file")) {
MultipartFile file = file_list.get("file");
// 获取文件名
String fileName = file.getOriginalFilename();
if (file != null) {
//把文件保存的路径跟名字
File saveFile = new File(path, fileName);
// 如果文件夹不存在,自动创建该文件夹
if (!saveFile.exists()) {
saveFile.mkdirs();
}
//spring的transferTo保存文件方法
file.transferTo(saveFile);
modelMap.put("msg", "success");
//modelMap.put("file", "\\" +uptype+"/" + newFileName);
}
}
}else {
modelMap.put("file", "不允许上传空文件");
}
String json = JSON.toJSONString(modelMap);
return json;
} catch (Exception e) {
e.printStackTrace();
modelMap.put("file", "error");
String json = JSON.toJSONString(modelMap);
return json;
}
}
/**
* 上传
* @Title: upload
* @param: @param request
* @param: @param path
* @param: @param uptype
* @param: @return
* @return: String
* @throws
*/
public static String upload2(HttpServletRequest request,String path,String uptype){
Map<String, String> modelMap = new HashMap<>();
try {
MultipartHttpServletRequest rq = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> file_list = rq.getFileMap();
if (file_list != null && file_list.size() > 0) {
if (file_list.containsKey("file")) {
MultipartFile file = file_list.get("file");
// 获取文件名
String fileName = file.getOriginalFilename();
if (file != null) {
//新图片名字
String newFileName = "";
//截取原来图片本来名字
String[] desp = fileName.split("\\.");
if (desp != null && desp.length > 0) {
String extendName = desp[desp.length - 1];
//时间加原来名字组成新名字
newFileName = new Date().getTime() + "." + extendName;
//把文件保存的路径跟名字
File saveFile = new File(path, newFileName);
// 如果文件夹不存在,自动创建该文件夹
if (!saveFile.exists()) {
saveFile.mkdirs();
}
//spring的transferTo保存文件方法
file.transferTo(saveFile);
modelMap.put("msg", "success");
//modelMap.put("file", "\\" +uptype+"/" + newFileName);
}
}
}
}else {
modelMap.put("file", "不允许上传空文件");
}
String json = JSON.toJSONString(modelMap);
return json;
} catch (Exception e) {
e.printStackTrace();
modelMap.put("file", "error");
String json = JSON.toJSONString(modelMap);
return json;
}
}
/**
* 验证文件夹是否存在
* <p>
* Title: isFolderExists
* </p>
* <p>
* Description:
* </p>
* @param strFolder @return
*/
public static boolean isFolderExists(String strFolder) {
File file = new File(strFolder);
if (!file.exists()) {
if (file.mkdir()) {
return true;
} else {
return false;
}
}
System.out.println("-----------------文件上传路径:" + strFolder);
return true;
}
/**
* 获取目录下所有文件(按时间排序)
* <p>
* Title: getFileSort
* </p>
* <p>
* Description:
* </p>
* @param path @return
*/
public static List<File> getFileSort(String path) {
List<File> list = getFiles(path, new ArrayList<File>());
if (list != null && list.size() > 0) {
Collections.sort(list, new Comparator<File>() {
public int compare(File file, File newFile) {
if (file.lastModified() < newFile.lastModified()) {// 降序<;升序>
return 1;
} else if (file.lastModified() == newFile.lastModified()) {
return 0;
} else {
return -1;
}
}
});
}
return list;
}
/**
* 获取目录下所有文件
* <p>
* Title: getFiles
* </p>
* <p>
* Description:
* </p>
* @param realpath @param files @return
*/
public static List<File> getFiles(String realpath, List<File> files) {
File realFile = new File(realpath);
if (realFile.isDirectory()) {
File[] subfiles = realFile.listFiles();
for (File file : subfiles) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files);
} else {
files.add(file);
}
}
}
return files;
}
}
/**
* 图片上传工具类
* @ClassName: PictureUtils
* @author: Amy
* @date: 2019年9月25日 下午5:42:20
* @Copyright:
*/
public class PictureUtils {
/**
* 图片上传1
* @Title: upload
* @param: @param request
* @param: @param file
* @param: @return
* @param: @throws IOException
* @return: String
* @throws
*/
public static String upload(HttpServletRequest request, MultipartFile file) {
Map<String, String> modelMap = new HashMap<>();
if (!file.isEmpty()) {
String path = request.getServletContext().getRealPath("upload");// 文件的上传路径
//String path = "/usr/local/tomcat-8.5.45/hospitalpicture";// 文件的上传路径
// 获取文件名
String fileName = file.getOriginalFilename();
// 获得文件后缀名称
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 规范时间格式
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileNamenew = new Random().nextInt(9000) + sf.format(new Date());
// 生成最新的文件名称
String newFileName = fileNamenew + "." + suffixName;
try {
// 指定的目录下
File dir = new File(path, newFileName);
// 如果文件夹不存在,自动创建该文件夹
if (!dir.exists()) {
dir.mkdirs();
}
// 将指定文件上传到指定的目录下
file.transferTo(dir);
} catch (Exception e) {
e.printStackTrace();
modelMap.put("msg", "error");
String json = JSON.toJSONString(modelMap);
return json;
}
modelMap.put("msg", "success");
modelMap.put("img", "\\upload/" + newFileName);
} else {
modelMap.put("msg", "不允许上传空文件");
}
String json = JSON.toJSONString(modelMap);
return json;
}
/**
* 图片上传2
* @Title: upload2
* @param: @param request
* @param: @return
* @param: @throws IOException
* @return: String
* @throws
*/
public static String upload2(HttpServletRequest request){
Map<String, String> modelMap = new HashMap<>();
try {
MultipartHttpServletRequest rq = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> file_list = rq.getFileMap();
if (file_list != null && file_list.size() > 0) {
if (file_list.containsKey("file")) {
String path = request.getServletContext().getRealPath("upload");// 文件的上传路径
//String path = "/usr/local/tomcat-8.5.45/hospitalpicture";// 文件的上传路径
MultipartFile file = file_list.get("file");
// 获取文件名
String fileName = file.getOriginalFilename();
if (file != null) {
//新图片名字
String newFileName = "";
//截取原来图片本来名字
String[] desp = fileName.split("\\.");
if (desp != null && desp.length > 0) {
String extendName = desp[desp.length - 1];
//时间加原来名字组成新名字
newFileName = new Date().getTime() + "." + extendName;
//把文件保存的路径跟名字
File saveFile = new File(path, newFileName);
// 如果文件夹不存在,自动创建该文件夹
if (!saveFile.exists()) {
saveFile.mkdirs();
}
//spring的transferTo保存文件方法
file.transferTo(saveFile);
modelMap.put("msg", "success");
modelMap.put("img", "\\upload/" + newFileName);
}
}
}
}else {
modelMap.put("msg", "不允许上传空文件");
}
String json = JSON.toJSONString(modelMap);
return json;
} catch (Exception e) {
e.printStackTrace();
modelMap.put("msg", "error");
String json = JSON.toJSONString(modelMap);
return json;
}
}
/**
* 图片上传3
* @Title: upload3
* @param: @param request
* @param: @param file
* @param: @return
* @return: String
* @throws
*/
public static JSONObject upload3(HttpServletRequest request,@RequestParam("file") MultipartFile file) {
Assert.notNull(file, "上传文件不能为空");
String src="\\upload/";
String path = request.getServletContext().getRealPath("upload");// 文件的上传路径
//String path = "/usr/local/tomcat-8.5.45/hospitalpicture";// 文件的上传路径
JSONObject json = new JSONObject();
// 获取文件名
String fileName = file.getOriginalFilename();
// 获得文件后缀名称
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 规范时间格式
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileNamenew = new Random().nextInt(9000) + sf.format(new Date());
// 生成最新的文件名称
String newFileName = fileNamenew + "." + suffixName;
File dir = new File(path, newFileName);
src=src+newFileName;
if (!dir.exists()) {
dir.mkdirs();
}
try {
file.transferTo(dir);
json.put("msg","上传成功");
json.put("code",0);
json.put("src",src);
} catch (IOException e) {
e.printStackTrace();
json.put("msg","上传失败");
json.put("code",1);
}
return json;
}
/**
* 多图片上传
* @Title: fileups
* @param: @param files
* @param: @param request
* @param: @return
* @return: String
* @throws
*/
public static String fileups(MultipartFile[] files, HttpServletRequest request) {
Map<String, String> modelMap = new HashMap<>();
// 获取文件上传路径
String path = request.getServletContext().getRealPath("upload");// 文件的上传路径
//String path = "/usr/local/tomcat-8.5.45/hospitalpicture";// 文件的上传路径
String str = "";
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (!files[i].isEmpty()) {
String fileName = files[i].getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf(".")); // 获取后缀名
String newName = new Date().getTime() + fileType;
File dir = new File(path, newName);
if (!dir.exists()) {
dir.mkdirs();
}
try {
files[i].transferTo(dir);
str += (newName + ";");
} catch (IOException e) {
e.printStackTrace();
modelMap.put("msg", "上传出错!");
break;
}
}else {
modelMap.put("msg", "不允许上传空文件");
break;
}
}
if (str.length()>0) {
String s = str.substring(0, str.length() - 1);
modelMap.put("msg", "success");
modelMap.put("img", "\\upload/" + s);
}
} else {
modelMap.put("msg", "不允许上传空文件");
}
String json = JSON.toJSONString(modelMap);
return json;
}
/**
* 上传图片
*<p>Title: upload</p>
*<p>Description: </p>
* @param request
* @param pictureFile
* @return
* @throws IOException
*/
public static String upload4(HttpServletRequest request,
MultipartFile pictureFile) throws IOException {
String imgPath = null;//装配后的图片地址
//上传图片
if(pictureFile!=null&&!pictureFile.isEmpty()){
// 使用UUID给图片重命名,并去掉四个“-”
String name = UUID.randomUUID().toString().replaceAll("-", "");
// 获取文件的扩展名
String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
// 设置图片上传路径
String url = request.getSession().getServletContext().getRealPath("/upload");
// 检验文件夹是否存在
isFolderExists(url);
// 以绝对路径保存重名命后的图片
pictureFile.transferTo(new File(url + "/" + name + "." + ext));
// 装配图片地址
imgPath = "upload/" + name + "." + ext;
}
return imgPath;
}
/**
* 验证文件夹是否存在
*<p>Title: isFolderExists</p>
*<p>Description: </p>
* @param strFolder
* @return
*/
public static boolean isFolderExists(String strFolder){
File file = new File(strFolder);
if (!file.exists())
{
if (file.mkdir())
{
return true;
}
else{
return false;
}
}
System.out.println("-----------------文件上传路径:"+strFolder);
return true;
}
/**
* 获取目录下所有文件(按时间排序)
*<p>Title: getFileSort</p>
*<p>Description: </p>
* @param path
* @return
*/
public static List<File> getFileSort(String path) {
List<File> list = getFiles(path, new ArrayList<File>());
if (list != null && list.size() > 0) {
Collections.sort(list, new Comparator<File>() {
public int compare(File file, File newFile) {
if (file.lastModified() < newFile.lastModified()) {//降序<;升序>
return 1;
} else if (file.lastModified() == newFile.lastModified()) {
return 0;
} else {
return -1;
}
}
});
}
return list;
}
/**
* 获取目录下所有文件
*<p>Title: getFiles</p>
*<p>Description: </p>
* @param realpath
* @param files
* @return
*/
public static List<File> getFiles(String realpath, List<File> files) {
File realFile = new File(realpath);
if (realFile.isDirectory()) {
File[] subfiles = realFile.listFiles();
for (File file : subfiles) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files);
} else {
files.add(file);
}
}
}
return files;
}
}
服务端Controller
/**
* 日志文件上传接口
* @Title: uploadPicture
* @param: @param request
* @param: @param response
* @param: @throws Exception
* @return: void
* @throws
*/
@RequestMapping(value = "/logfile", method = RequestMethod.POST)
public void uploadPicture(HttpServletRequest request, HttpServletResponse response){
System.out.println("uploadfile");
String path = "/var/www/html/chinaivf/ivfapp/crash_log";
String uptype = "logfile";
String json = UpfileUtils.upload(request,path,uptype);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(json);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (writer != null) {
writer.close();
}
}
}
/**
* 上传图片接口1 @Title: updatePicture @param: @param file @param: @param
* request @param: @return @param: @throws IOException @return: String @throws
*/
@RequestMapping(value = "/addpicture")
public void updatePicture(@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request, HttpServletResponse response){
System.out.println("addpicture");
String json = PictureUtils.upload(request, file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(json);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (writer != null) {
writer.close();
}
}
}
/**
* 图片上传接口2
* @Title: uploadPicture
* @param: @param request
* @param: @param response
* @param: @throws Exception
* @return: void
* @throws
*/
@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
public void uploadPicture(HttpServletRequest request, HttpServletResponse response){
System.out.println("uploadImg");
String json = PictureUtils.upload2(request);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(json);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (writer != null) {
writer.close();
}
}
}
/**
* 多图片上传
* @Title: fileup
* @param: @param files
* @param: @param request
* @param: @param response
* @return: void
* @throws
*/
@RequestMapping(value = "/fileups", method = { RequestMethod.POST })
public void fileup(@RequestParam("files")MultipartFile[] files, HttpServletRequest request, HttpServletResponse response){
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
String json = PictureUtils.fileups(files, request);
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(json);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (writer != null) {
writer.close();
}
}
}
APP端工具类
public class OkHttpUtil {
public static void upload(String filePath){
OkHttpClient client=new OkHttpClient();
File file=new File(filePath);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("multipart/form-data"), file))
.addFormDataPart("type","App")
.addFormDataPart("nowuser","54872154")
.build();
Request request = new Request.Builder()
.url("http://longma.chinaivf.com/file/logfile")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d("onUpload","failure"+e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
Log.d("onUpload","success"+response.body().string()+","+response.code());
}
});
}
}