基本的单图片上传(支持springboot)

前端

页面

	 <!--multiple 为多选择  -->
      <input type="file" id="file"  style="display: inline-block"/>
      <button ng-click="uploadFile()" class="btn btn-primary"
              style="margin: 12px 12px" type="button" style="display: inline-block">
          上传
      </button>

发送请求

this.uploadFile = function () {
        var formData = new FormData(); //上传文件的数据模型
        //参数名对应contorller中的参数名  参数内容
        formData.append("uploadFile", file.files[0]); //文件上传框的id必须是和append的第二个参数一致
        //多文件 file.files遍历   formData.append 追加 使用  multipart/form-data
        return $http({
            method : 'post',	//使用post提交方式
            url : "upload/upload.do", //请路径
            data : formData,
            headers : {'Content-Type' : undefined}, //上传文件使用undefined,默认text/plain  多文件使用 multipart/form-data
            transformRequest : angular.identity  //对整个表单进行二进制序列化
        });

    }

后端

springBoot 使用到的坐标

	 <!--json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>

        <!-- 文件上传 -->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <!--  时间工具   -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>

        <!-- jdom2解析xml接口
            JDOM是一种使用 XML(标准通用标记语言下的一个子集) 的独特 Java 工具包,它的设计包含 Java 语言的语法乃至语义
         -->
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom2</artifactId>
            <version>2.0.5</version>
        </dependency>

工具类中提取的方法

/**
	 *
	 * @param mFile   		接收到的文件数组
	 * @param serverPath	服务器路径
	 * @param isSimple		true  单文件上传   false 多文件上传
	 * @return			返回图片路径信息
	 * @throws IOException
	 */
	public static String uploadFile(MultipartFile[] mFile, String serverPath, boolean isSimple) throws IOException {
		// 获取上传文件信息
		//System.err.println(JSON.toJSONString(mFile));  //输出上传文件信息
		String imgurl = "";  //图片路径容器
		if (mFile != null && mFile.length > 0) {  //如果有文件
			if (isSimple) {  //单文件
				imgurl = handleUpload(mFile[0], serverPath);  //获取
			} else {
				List<String> str = new ArrayList<String>();
				for (MultipartFile val : mFile) {
					str.add(handleUpload(val, serverPath)); //进行遍历
				}
				imgurl = String.join(",", str); //把字符串数组 转成以一个变量分割的字符串
			}
		}
		return imgurl;
	}

	/**
	 * 上传原始图片
	 *
	 * @param val				文件内容  (单个)
	 * @param serverPath		服务器路径
	 * @return	图片路径
	 * @throws IOException
	 */
	public static String handleUpload(MultipartFile val, String serverPath) throws IOException {
		String fileName = "";  //
		if (!val.isEmpty()) {   //如果文件不为空
			String oldFileName = val.getOriginalFilename(); // 获取上传文件的原名
			File dir = new File(serverPath);				//	创建文件对象
			// File parent = dest.getParentFile();

			//isFile() 文件存在且是一个标准文件时,返回true;否则返回false
			//exists() 当此抽象路径名表示的文件或目录存在时,返回true;否则返回false;
			//dir.isDirectory()  是检查一个对象是否是文件夹  是则返回true,否则返回false。
			if (!dir.exists() || !dir.isDirectory()) {     // 文件或目录不存在  或 路径不是文件夹
				dir.mkdirs();      //创建目录 文件夹
			}
			//此处2行 使用了工具类  可以自己定义命名规则
			long rand = DateUtils.currentTimeMillis();   //获取当前时间戳
			String date = DateUtils.getSysCurrentDay2(); //获取当前年月日
			
			String imgType = FilenameUtils.getExtension(oldFileName); //获取图片后缀名
			fileName = date + rand + "." + imgType;       //拼接新的 图片名称  年月日 + 时间戳  + 图片后缀名
			// System.getProperty("file.separator")
			//file.separator这个代表系统目录中的间隔符 斜线    解决兼容问题  可能是单双斜杠
			String newUrl = serverPath + File.separator + fileName;  // 图片的路径
			File newFile = new File(newUrl);	//创建文件对象
			// 保存文件  文件类型成了application/octet-stream 二进制了
			FileUtils.copyInputStreamToFile(val.getInputStream(), newFile);
			// val.transferTo(dest);
		}
		return fileName;
	}

附上工具类

时间工具类

package com.example.test.util;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
	
	/**
	 * <li>参数数组</li><br/>
	 * 0:yyyyMMdd<br/>1:yyyy-MM-dd<br/>2:yyyy-MM-dd HH:mm<br/>3:yyyy-MM-dd HH:mm:ss<br/>4:yyyy/MM/dd<br/>
	 * 5:yyyy/MM/dd HH:mm<br/>6:yyyy/MM/dd HH:mm:ss<br/>7:HH:mm:ss[时间]<br/>8:yyyy[年份]<br/>9:MM[月份]<br/>
	 * 10.dd[天]<br/>11.E[星期几]<br/>12.yyyyMMddHHmmss<br/>
	 */
	public static String[] parsePatterns = {"yyyyMMdd","yyyy-MM-dd","yyyy-MM-dd HH:mm","yyyy-MM-dd HH:mm:ss", 
			"yyyy/MM/dd","yyyy/MM/dd HH:mm","yyyy/MM/dd HH:mm:ss","HH:mm:ss","yyyy","MM","dd","E", 
			"yyyyMMddHHmmss", "MM/d/yy", "dd/MM/yyyy"};

    public DateUtils() {

    }
    
	/**
	 * <li>得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"</li>
	 *  @param  pattern 可参考参数组parsePatterns
	 */
	public static String getDate(String pattern) {
		return DateFormatUtils.format(new Date(), pattern);
	}	
	/**
	 * <li>得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"</li>
	 * @param  date    日期类  
	 * @param  pattern 可参考参数组parsePatterns
	 */
	public static String formatDate(Date date, Object... pattern) {
		String formatDate = null;
		if (pattern != null && pattern.length > 0) {
			formatDate = DateFormatUtils.format(date, pattern[0].toString());
		} else {
			formatDate = DateFormatUtils.format(date,parsePatterns[1]);
		}
		return formatDate;
	}	
	/**
	 * <li>日期型字符串转化为日期 格式</li>
	 * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
	 */
	public static Date parseDate(Object str) {
		if (str == null){
			return null;
		}
		try {
			return parseDate(str.toString(), parsePatterns);
		} catch (ParseException e) {
			return null;
		}
	}
	/**
	 * <li>获取过去的天数</li>
	 * @param date
	 * @return
	 */
	public static long pastDays(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(24*60*60*1000);
	}
	/**
	 * <li>获取输入日期开始时间</li>
	 * @param date
	 * @return
	 */
	public static Date getDateStart(Date date) {
		if(date==null) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date= sdf.parse(formatDate(date, "yyyy-MM-dd")+" 00:00:00");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	/**
	 * <li>获取输入日期结束时间</li>
	 * @param date
	 * @return
	 */
	public static Date getDateEnd(Date date) {
		if(date==null) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date= sdf.parse(formatDate(date, "yyyy-MM-dd") +" 23:59:59");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	/**
	 * <li>按输入日期加分钟</li>
	 * @param date   日期
	 * @param recordPeriodMinute 分钟数
	 * @return
	 */
	public static Date addMinutes(Date recordTime, int recordPeriodMinute) {
		Calendar c = Calendar.getInstance();
		c.setTime(recordTime);
		c.add(Calendar.MINUTE, recordPeriodMinute);
		return c.getTime();
	}
	/**
	 * <li>按输入日期加毫秒</li>
	 * @param date   日期
	 * @param recordPeriodSecond 毫秒数
	 * @return
	 */
	public static Date addSeconds(Date recordTime, int recordPeriodSecond) {
		Calendar c = Calendar.getInstance();
		c.setTime(recordTime);
		c.add(Calendar.SECOND, recordPeriodSecond);
		return c.getTime();
	}
	/**
	 * <li>校验日期是否合法</li>
	 * @param date 日期
	 * @return
	 */
	public static boolean isValidDate(String date) {
		DateFormat fmt = new SimpleDateFormat(parsePatterns[1]);
		try {
			fmt.parse(date);
			return true;
		} catch (Exception e) {
			// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
			return false;
		}
	}	
	  /**
     * <li>时间相减得到相差年数</li>
     * @param startTime 开始日期
     * @param endTime   结束日期
     * @return
     */
	public static int getDiffYear(String startTime,String endTime) {
		DateFormat fmt = new SimpleDateFormat(parsePatterns[1]);
		try {
			int years=(int) (((fmt.parse(endTime).getTime()-fmt.parse(startTime).getTime())/ (1000 * 60 * 60 * 24))/365);
			return years;
		} catch (Exception e) {
			e.printStackTrace();
			// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
			return 0;
		}
	}
	  /**
     * <li>功能描述:时间相减得到天数</li>
     * @param startTime 开始日期
     * @param endTime   结束日期
     * @return
     */
    public static long getDaySub(String startTime,String endTime){
        long day=0;
        SimpleDateFormat format = new SimpleDateFormat(parsePatterns[1]);
        Date beginDate = null;
        Date endDate = null;   
            try {
				beginDate = format.parse(startTime);
				endDate= format.parse(endTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}
            day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);   
        return day;
    }
    /**
     * <li>得到n天之后的日期</li>
     * @param days
     * @return
     */
    public static String getAfterDayDate(String days) {
    	int daysInt = Integer.parseInt(days); 	
        Calendar canlendar = Calendar.getInstance(); 
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();
        SimpleDateFormat sdfd = new SimpleDateFormat((parsePatterns[3]));
        String dateStr = sdfd.format(date);     
        return dateStr;
    }
    
    /**
     * <li>得到n天之后是周几</li>
     * @param days
     * @return
     */
    public static String getAfterDayWeek(String days) {
    	int daysInt = Integer.parseInt(days);	
        Calendar canlendar = Calendar.getInstance(); 
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();     
        SimpleDateFormat sdf = new SimpleDateFormat(parsePatterns[11]);
        String dateStr = sdf.format(date);
        return dateStr;
    }
    /**
	 * 把时间根据时、分、秒转换为时间段
	 * @param  Object  可选其1值{ "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
	 * @author String ?日前或?小时前或?分钟前?秒前
	 */
	public static String getTimes(Object str){
		String resultTimes = "";
		Date now;
		Date date=parseDate(str);
		now = new Date();
		long times = now.getTime() - date.getTime();
		long day = times / (24 * 60 * 60 * 1000);
		long hour = (times / (60 * 60 * 1000) - day * 24);
		long min = ((times / (60 * 1000)) - day * 24 * 60 - hour * 60);
		long sec = (times / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		StringBuffer sb = new StringBuffer();
		if(day>0){
			sb.append(day + "日前");
		}else if (hour > 0) {
			sb.append(hour + "小时前");
		} else if (min > 0) {
			sb.append(min + "分钟前");
		} else if (sec >0){
			sb.append(sec + "秒前");
		}else if(times>=0){
			sb.append(times + "毫秒前");
		}else{
			sb.append("超前毫秒数:"+times);
		}
		resultTimes = sb.toString();
	    return resultTimes;
	}
		
    /** 
     * 将微信消息中的CreateTime转换成标准格式的时间Date
     * @param createTime 消息创建时间 
     * @return 
     */  
    public static Date formatTime(long createTime) {  
    	long msgCreateTime =createTime*1000L;  
        return new Date(msgCreateTime);  
    }  

    public static Date parse(String dateString, String formatString) {
        SimpleDateFormat df = new SimpleDateFormat(formatString);
        try {
            return df.parse(dateString);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 给定日期增加一天
     * @param date
     * @param value
     * @return
     */
    public static Date addDay(Date date, int value) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.add(Calendar.DAY_OF_YEAR, value);
        return now.getTime();
    }

    /**
     * 将字符串转换成为date
     * @param Patten
     * @param str
     * @return
     */
    private static Date strToDate(String Patten, String str) {
        Date date = null;
        SimpleDateFormat format = null;
        format = new SimpleDateFormat(Patten);
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            System.out.println("strToDateParseException::>>" + e.toString());
        } catch (Exception e) {
            System.out.println("strToDatePException::>>" + e.toString());
        }
        return date;
    }

    /**
     * 将时间转换成为字符串
     * @param Patten
     * @param date
     * @return
     */
    private static String dateToStr(String Patten, Date date) {
        String str = null;
        SimpleDateFormat format = null;
        format = new SimpleDateFormat(Patten);
        try {
            str = format.format(date);
        } catch (Exception e) {
            System.out.println("dateToStrPException::>>" + e.toString());
        }
        return str;
    }

    /**
     * 将以秒为单位的时间转换为字符串
     * @param datetime
     * @return
     */
    public static String datetimeToStr(Date datetime) {
        return dateToStr("yyyy-MM-dd HH:mm:ss", datetime);
    }


    /**
     * 将日期转换成为以天为单位的时间
     * @param day
     * @return
     */
    public static String dayToStr(Date day) {
        if (day == null){
            return "";
        }
        return dateToStr("yyyy-MM-dd", day);
    }

    /**
     * 将以天为单位的时间转换为字符转
     * @param str
     * @return
     */
    public static Date strToDay(String str) {
        return strToDate("yyyy-MM-dd", str);
    }

    /**
     * 格式化时间
     * 单位天
     * @param str
     * @return
     */
    public static String dateFormat(String str){
    	return dayToStr(strToDay(str));
    }

    /**
     * 将以秒为单位的字符转换成为时间
     * @param str
     * @return
     */
    public static Date strToTime(String str) {
        return strToDate("yyyy-MM-dd HH:mm:ss", str);
    }


    /**
     * 得到当前时间,以年为单位
     * @return
     */
	public static String getSysCurrentYear() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        String strDate = df.format(now);
        return strDate;
    }

    /**
     * 得到当前时间,以月为单位
     * @return
     */
	public static String getSysCurrentMonth() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        String strDate = df.format(now);
        return strDate;
    }

	public static String getSysCurrentMonth2() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
        String strDate = df.format(now);
        return strDate;
    }

    /**
     * 得到当前时间,以天为单位
     * @return
     */
	public static String getSysCurrentDay() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = df.format(now);
        return strDate;
    }

	public static String getSysCurrentDay2() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String strDate = df.format(now);
        return strDate;
    }

	public static String getSysCurrentDay3() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("dd");
        String strDate = df.format(now);
        return strDate;
    }

    /**
     * 得到当前时间,以小时为单位
     * @return
     */
	public static String getSysCurrentHours() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
        String strDate = df.format(now);
        return strDate;
    }

	public static String getSysCurrentH() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("HH");
        String strDate = df.format(now);
        return strDate;
    }

    /**
     * 得到当前时间,以秒为单位
     * @return
     */
	public static String getSysCurAllTime() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = df.format(now);
        return strDate;
    }

	public static String getSysCurAllTime2() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String strDate = df.format(now);
        return strDate;
    }

	public static String getSysCurAllTime3() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = df.format(now);
        return strDate;
    }
    /**
     * 得到当前时间
     * @return
     */
	public static String getSysCurrentTime() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        String strDate = df.format(now);
        return strDate;
    }

    /**
     * 当前日期加减天数,days为正表示加days天,为负表示减days天
     * @param days
     * @return
     * @throws Exception
     */
    public static String convertAddDay(int days) throws Exception {

		String str = getSysCurrentDay();
        Date dt = strToDate("yyyy-MM-dd", str);

        Calendar current = Calendar.getInstance();
        current.setTime(dt);
        current.add(Calendar.DATE, days);
        Date dt1 = current.getTime();

        return dateToStr("yyyy-MM-dd", dt1);
    }
    
    /**
     * 指定日期加上指定天数
     * @param date
     * @param days
     * @return
     * @throws Exception
     */
    public static String convertAddDay(String date, int days) throws Exception {
        Date dt = strToDate("yyyy-MM-dd", date);
        Calendar current = Calendar.getInstance();
        current.setTime(dt);
        current.add(Calendar.DATE, days);
        Date dt1 = current.getTime();

        return dateToStr("yyyy-MM-dd", dt1);
    }
    
    /**
     * 当前时间加减小时,hours为正表示加hours小时,为负表示减hours小时
     * @param hours
     * @return
     * @throws Exception
     */
    public static String convertAddHours(int hours) throws Exception {
		String str = getSysCurrentHours();
        Date dt = strToDate("yyyy-MM-dd HH", str);

        Calendar current = Calendar.getInstance();
        current.setTime(dt);
        current.add(Calendar.HOUR, hours);
        Date dt1 = current.getTime();

        return dateToStr("yyyy-MM-dd HH", dt1);
    }

    /**
	 * 返回系统当前时间戳(以毫秒为单位)
	 * 
	 * @return
	 * @throws Exception
	 */
    public static long currentTimeMillis() {
        return System.currentTimeMillis();  //返回当前时间戳
    }

    /**
	 * 计算两个时间之间的差值,单位:毫秒;第二个时间大于第一个时间正值
	 * @param strdate1 第一个时间
	 * @param strdate2 第二个时间
	 * @param Patten 是个格式化参数
	 * @return
	 * @throws Exception
	 */
	public static long dateSubtraction(String strdate1, String strdate2, String Patten) {
		Date date1 = strToDate(Patten,strdate1);
		Date date2 = strToDate(Patten,strdate2);
		long diff =  date2.getTime()-date1.getTime(); 
		return diff;
	}

	public static boolean dateInTimes(String tdate, String date1, String date2, String patten){
        return dateSubtraction(date1,tdate,patten)>=0 && dateSubtraction(tdate,date2,patten)>=0;
    }
	
	/**
	 * 计算两个时间相差的天数
	 * @param strdate1
	 * @param strdate2
	 * @return
	 * @throws Exception
	 */
	public static long daySubtraction(String strdate1, String strdate2) throws Exception {
		long times = dateSubtraction(strdate1,strdate2,"yyyy-MM-dd");
		long diff = (times/1000/60/60/24);
		return diff;
	}
	
	public static int getAge(String birthday) {
		String now = getSysCurrentDay();
		int age = 0;
		try {
			long days = daySubtraction(birthday, now);
			double n = days/365.2422;
			age = (int) Math.ceil(n);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return age;
	}
	
	/**
     * 将时间字符串转换为毫秒
     * @param datetime
     * @return
     */
    public static long datestrToMill(String datetime) {
    	long millionSeconds = 0;
    	try {
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        	millionSeconds = sdf.parse(datetime).getTime();//毫秒
        } catch (Exception e) {
        	System.out.println("datestrToMillException::>>" + e.toString());
        }
        return millionSeconds;
    }
    
    /**
     * 将毫秒转换为指定格式的日期
     * @param mill
     * @return
     */
    public static String convertMillToDate(long mill){
    	Date date = new Date(mill);
    	SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	return sfd.format(date);
    }
    
    public static String getTimeEquationFormat(String endtime, String starttime) throws Exception {
		int second=getTimeEquation(endtime,starttime);
		return getSecond(second);
	}
    
    /**
	 * 求时差
	 * @param endtime
	 * @param starttime
	 * @return 返回相差的秒数
	 * @throws Exception
	 */
	public static int getTimeEquation(String endtime, String starttime) throws Exception {
		Date d1=strToDate("yyyy-MM-dd HH:mm:ss",starttime);
		Date d2=strToDate("yyyy-MM-dd HH:mm:ss",endtime);
		int time_c=Integer.valueOf((d2.getTime()-d1.getTime())/1000+"");
		return time_c;
	}
	
	/**
	 * 将秒数转换为以 DD hh:mm:ss 的形式
	 * @param second
	 * @return
	 * @throws Exception
	 */
	public static String getSecondToDate(int second) throws Exception {
		//剩余时间
		int lave=0;
		
		int d=0;
		int h=0;
		int m=0;
		int s=0;
		//计算天
		d=second/(24*3600);
		lave=second-d*24*3600;
		h=lave/3600;
		lave=lave-h*3600;
		m=lave/60;
		lave=lave-m*60;
		s=lave;
		return d+" "+h+":"+m+":"+s;
	}
	
	public static String getSecond(int second) throws Exception {
		//剩余时间
		int lave=0;
		
		int d=0;
		int h=0;
		int m=0;
		int s=0;
		//计算天
		d=second/(24*3600);
		lave=second-d*24*3600;
		h=lave/3600;
		lave=lave-h*3600;
		m=lave/60;
		lave=lave-m*60;
		s=lave;
		return d+"天"+h+"小时"+m+"分"+s+"秒";
	}

    public static List<String> getLastDays(int day) {
        List<String> list = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        list.add(sdf.format(calendar.getTime()));
        for(int i=day-1;i>0;i--){
            calendar.add(Calendar.DATE, -1);
            list.add(sdf.format(calendar.getTime()));
        }
        Collections.reverse(list);
        return list;
    }

    public static List<Date> findDates(Date dBegin, Date dEnd)
    {
        List lDate = new ArrayList();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())){
            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }
    
    /**
     * 根据给定年数,返回N年前日期
     * @Title: getYearsOld
     * @Description: TODO
     * @param nYears
     * @return   
     * @return String    返回类型
     */
    public static String getNYearsOldDateStr(int nYears) {
    	Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.YEAR, -nYears);
		String day = DateUtils.dayToStr(cal.getTime());
		return day;
    }
	
    public static void main(String[] args) throws Exception {
    	System.out.println(getAge("1969-01-29"));
//        BufferedReader br = null;
//        BufferedWriter bw = null;
//        br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("F:/gps/2.log"))));
//        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("F:/gps/3.txt"))));
//        String str = null;
//        try {
//            while ((str = br.readLine()) != null) {
//                String[] dd = str.split(",");
//                if(dd.length>0){
//                    bw.write(dd[3]+"\t"+dd[2]);
//                    bw.newLine();
//                }
//            }
//            bw.flush();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}

xml解析工具类 包含微信部分

package com.example.test.util;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;

import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLUtil {

	/**
	 * description: 解析微信通知xml
	 * 
	 * @param xml
	 * @return
	 * @author ex_yangxiaoyi
	 * @see
	 */
	@SuppressWarnings({ "unused", "rawtypes", "unchecked" })
	public static Map parseXmlToList(String xml) {
		Map retMap = new HashMap();
		try {
			StringReader read = new StringReader(xml);
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			// 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			// 通过输入源构造一个Document
			Document doc = (Document) sb.build(source);
			Element root = doc.getRootElement();// 指向根节点
			List<Element> es = root.getChildren();
			if (es != null && es.size() != 0) {
				for (Element element : es) {
					retMap.put(element.getName(), element.getValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;

	}

}

此方法中用到的上传图片的工具类

package com.example.test.util;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZTools {

	public static Map getMwebUrl(String url, String xmlParam) {
		String jsonStr = null;
		HttpClient httpClient = new HttpClient();
		Map map = new HashMap();
		try {
			PostMethod method = null;
			RequestEntity reqEntity = new StringRequestEntity(xmlParam, "text/json", "UTF-8");
			method = new PostMethod(url);
			method.setRequestEntity(reqEntity);
			method.addRequestHeader("Content-Type", "application/json;charset=utf-8");
			httpClient.executeMethod(method);
			StringBuffer resBodyBuf = new StringBuffer();
			byte[] responseBody = new byte[1024];
			int readCount = 0;
			BufferedInputStream is = new BufferedInputStream(method.getResponseBodyAsStream());
			while ((readCount = is.read(responseBody, 0, responseBody.length)) != -1) {
				resBodyBuf.append(new String(responseBody, 0, readCount, "utf-8"));
			}
			jsonStr = resBodyBuf.toString();
			System.out.println(jsonStr);
			map = XMLUtil.parseXmlToList(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 获取用户实际ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	/* 文件删除 */
	public static void deleteFile(String fileOldname, String serverPath) {
		try {
			if (StringUtil.isNotEmpty(fileOldname)) {
				File oldFile = new File(serverPath + File.separator + fileOldname);
				if (oldFile.exists() && oldFile.isFile()) {
					oldFile.delete();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *
	 * @param mFile   		接收到的文件数组
	 * @param serverPath	服务器路径
	 * @param isSimple		true  单文件上传   false 多文件上传
	 * @return			返回图片路径信息
	 * @throws IOException
	 */
	public static String uploadFile(MultipartFile[] mFile, String serverPath, boolean isSimple) throws IOException {
		// 获取上传文件信息
		//System.err.println(JSON.toJSONString(mFile));  //输出上传文件信息
		String imgurl = "";  //图片路径容器
		if (mFile != null && mFile.length > 0) {  //如果有文件
			if (isSimple) {  //单文件
				imgurl = handleUpload(mFile[0], serverPath);  //获取
			} else {
				List<String> str = new ArrayList<String>();
				for (MultipartFile val : mFile) {
					str.add(handleUpload(val, serverPath)); //进行遍历
				}
				imgurl = String.join(",", str); //把字符串数组 转成以一个变量分割的字符串
			}
		}
		return imgurl;
	}

	/**
	 * 上传原始图片
	 *
	 * @param val				文件内容  (单个)
	 * @param serverPath		服务器路径
	 * @return	图片路径
	 * @throws IOException
	 */
	public static String handleUpload(MultipartFile val, String serverPath) throws IOException {
		String fileName = "";  //
		if (!val.isEmpty()) {   //如果文件不为空
			String oldFileName = val.getOriginalFilename(); // 获取上传文件的原名
			File dir = new File(serverPath);				//	创建文件对象
			// File parent = dest.getParentFile();

			//isFile() 文件存在且是一个标准文件时,返回true;否则返回false
			//exists() 当此抽象路径名表示的文件或目录存在时,返回true;否则返回false;
			//dir.isDirectory()  是检查一个对象是否是文件夹  是则返回true,否则返回false。
			if (!dir.exists() || !dir.isDirectory()) {     // 文件或目录不存在  或 路径不是文件夹
				dir.mkdirs();      //创建目录 文件夹
			}
			long rand = DateUtils.currentTimeMillis();   //获取当前时间戳
			String date = DateUtils.getSysCurrentDay2(); //获取当前年月日
			String imgType = FilenameUtils.getExtension(oldFileName); //获取图片后缀名
			fileName = date + rand + "." + imgType;       //拼接新的 图片名称  年月日 + 时间戳  + 图片后缀名
			// System.getProperty("file.separator")
			//file.separator这个代表系统目录中的间隔符 斜线    解决兼容问题  可能是单双斜杠
			String newUrl = serverPath + File.separator + fileName;  // 图片的路径
			File newFile = new File(newUrl);	//创建文件对象
			// 保存文件  文件类型成了application/octet-stream 二进制了
			FileUtils.copyInputStreamToFile(val.getInputStream(), newFile);
			// val.transferTo(dest);
		}
		return fileName;
	}


	/**
	 * 对字节数组字符串进行Base64解码并生成图片
	 *
	 * @Title: Base64ToImage
	 * @param imgStr
	 *            base64字符串
	 * @param imgFilePath
	 *            保存路径
	 * @return String 返回类型
	 */
	public static String Base64ToImage(String imgStr, String imgFilePath) {
		if (StringUtil.isEmpty(imgStr)) // 图像数据为空
			return null;
		long rand = DateUtils.currentTimeMillis();
		String date = DateUtils.getSysCurrentDay2();
		String fileName = date + rand + ".jpeg";
		// System.getProperty("file.separator")
		String newUrl = imgFilePath + File.separator + fileName;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(newUrl);
			out.write(b);
			out.flush();
			out.close();
			return fileName;
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * @Description: 根据图片地址转换为base64编码字符串
	 * @Author:
	 * @CreateTime:
	 * @return
	 */
	public static String getImageBase64Str(String imgFile) {
		InputStream inputStream = null;
		byte[] data = null;
		try {
			inputStream = new FileInputStream(imgFile);
			data = new byte[inputStream.available()];
			inputStream.read(data);
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 加密
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);
	}

	public static void main(String[] args) {
//		System.err.println(getImageBase64Str("C:\\Users\\13911\\Pictures\\Camera Roll\\jinGong.jpg"));
		System.err.println(getImageBase64Str("C:\\Users\\13911\\Pictures\\Camera Roll\\jinGong.jpg"));
	}

}

### 回答1: 可以使用 Spring Boot 中的 MultipartFile 类来实现图片上传。 首先,在你的 Spring Boot 应用的启动类上加上 @EnableWebMvc 注解,然后在你的 Controller 类中,使用 @RequestParam 注解来接收图片文件,如下所示: ``` @RequestMapping(value="/upload", method=RequestMethod.POST) public String handleFileUpload(@RequestParam("file") MultipartFile file) { // 进行文件上传操作 } ``` 然后,可以使用 MultipartFile 的 getBytes() 方法来获取文件的字节数组,并使用 FileOutputStream 将字节数组写入到文件中,就可以完成文件的上传操作了。 还有,在你的 HTML 文件中,需要使用 <form> 标签并设置 enctype 为 "multipart/form-data",才能正确的发送文件。 示例代码: ``` <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="file"/> <button type="submit">上传</button> </form> ``` 希望这能帮到你! ### 回答2: 在Spring Boot中实现图片上传可以遵循以下步骤: 1. 在pom.xml文件中导入Spring Boot的web依赖。 ```xml <dependencies> <!-- Spring Boot Web依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> ``` 2. 创建一个Controller类,用于处理图片上传请求。可以使用`@RestController`注解将该类声明为一个控制器,并使用`@PostMapping`注解指定处理POST请求。 ```java @RestController public class ImageController { @PostMapping("/upload") public String uploadImage(@RequestParam("file") MultipartFile file) { // 处理文件上传,例如保存文件到本地磁盘或将文件存储到数据库等操作 // 注意:根据实际需求,可能需要进行文件格式验证、文件大小限制等操作 // 返回上传成功的消息 return "文件上传成功!"; } } ``` 3. 在application.properties中配置文件上传的相关属性。可以指定文件上传最大大小、临时文件存储路径等。 ```properties # 文件上传配置 spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB spring.servlet.multipart.enabled=true spring.http.multipart.enabled=true spring.servlet.multipart.temp-dir= # 设置临时文件目录 ``` 4. 创建一个HTML页面,用于上传图片。页面中使用`<form>`标签创建一个表,并将enctype属性设置为`multipart/form-data`,以支持文件上传。通过`<input>`标签的type属性设置为`file`,用户可以选择要上传图片文件。 ```html <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </form> ``` 5. 运行Spring Boot应用,并访问上传图片页面。选择一个图片文件后,点击上传按钮即可触发图片上传请求。Controller类中的`uploadImage`方法将会被调用,可以在该方法中处理文件上传操作。 以上就是Spring Boot实现图片上传的简示例。需要根据具体需求,进一步完善图片上传的验证、存储、处理等功能。 ### 回答3: 要使用Spring Boot实现图片上传,可以按照以下步骤进行操作。 1. 首先,需要在pom.xml文件中添加相关的依赖项,如spring-boot-starter-web、spring-boot-starter-actuator。 2. 在项目的配置文件application.properties中配置上传文件的存储路径,如:spring.servlet.multipart.location=/upload。 3. 创建一个控制器类,用于处理上传图片的请求。可以使用@Controller注解来标识该类,并使用@RequestParam注解定义文件上传参数。 ```java @Controller public class FileUploadController { @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile file) { // 执行文件上传操作 return "success"; } } ``` 4. 在上述控制器方法中,使用MultipartFile类型的参数来接收上传的文件。可以通过调用transferTo()方法将文件保存到指定路径。 ```java @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { // 获取文件名 String fileName = file.getOriginalFilename(); // 构建文件保存路径 String filePath = "D:/upload/" + fileName; // 保存文件到指定路径 file.transferTo(new File(filePath)); return "success"; } catch (IOException e) { e.printStackTrace(); return "error"; } } else { return "error"; } } ``` 5. 最后,在前端页面中创建一个表,用于上传文件。可以使用HTML的<input type="file">元素来定义文件选择框,并通过form标签来包裹。 ```html <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上传" /> </form> ``` 以上就是使用Spring Boot实现图片上传基本步骤。需要注意的是,还可以根据实际需求添加文件大小、类型等的校验以及异常处理等功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扶摇的星河

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值