用户头像上传

生来就可爱ヽ(ⅴ<●) 提交于 2020-03-13 12:22:46

用户头像上传

思路:

​ 将文件保存到指定路径

​ 为原文件名加上时间戳尽量避免文件名冲突

问题:

​ 上传到应用目录,重新部署项目需要将上传的文件目录拷贝出来。

文件上传Controller

@RequestMapping("/uploadAccountImage")
public Result uploadAccountImage(@RequestParam("userImage")MultipartFile userImage, HttpServletRequest request){
    try{
        log.info("[账户管理][账户头像上传]");
        String uploadPath = "upload/account/image";
        Map<String, String> uploadResult = fileService.upload(
            FileUtil.appendBeforeDot(userImage.getOriginalFilename(),"_", GetTimeUtil.getNowTimeStamp()),
            userImage,
            FileUtil.appendTimePath(uploadPath, FileUtil.TimeUnit.YEAR),
            request);
        log.info("[账户管理][账户头像上传]上传结果:uploadResult={}", JSONObject.toJSONString(uploadResult));
        String flag = uploadResult.get("flag");
        if("success".equals(flag)){
            return ResultFactory.buildSuccessResult(uploadResult);
        }else{
            return ResultFactory.buildFailResult(uploadResult.get("message"));
        }
    } catch (CardException e){
        return ResultFactory.buidResult(e.getCode(), e.getCardMessage(), null);
    } catch (Exception e){
        e.printStackTrace();
        log.error("[账户管理][账户头像上传]发生异常");
        return ResultFactory.buildFailResult("发生异常");
    }
}
{
    "code": 200,
    "message": "成功",
    "data": {
        "flag": "success",
        "webUrl": "upload/account/image/201911/中国图画_20191107163422723.png",
        "message": "文件上传成功"
    }
}

文件工具类

package com.yuantiao.smartcardms.util;

import org.apache.commons.lang3.RandomStringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @date: 2019/11/7 14:51
 */
public class FileUtil {
    /**
     * 为文件名称添加指定字符串。
     * @param srcFileName
     * @param add
     * @return
     */
    public static String appendBeforeDot(String srcFileName, String... add){
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < add.length; i++) {
            temp.append(add[i]);
        }
        String tempAddStr = temp.toString();

        StringBuilder sb = new StringBuilder(srcFileName);
        int i = sb.lastIndexOf(".");
        if(i == -1){
            sb.append(tempAddStr);
        }else{
            sb.insert(i, tempAddStr);
        }
        return sb.toString();
    }

    /**
     * web路径追加路径
     * @param webPath
     * @param addPath
     * @return
     */
    public static String appendWebPath(String webPath, String... addPath){
        StringBuilder result = new StringBuilder(trimSlash(webPath));
        for (int i = 0; i < addPath.length; i++) {
            result.append("/").append(trimSlash(addPath[i]));
        }
        return result.toString();
    }

    public static String trimSlash(String str){
        if(str.startsWith("/"))
            str = str.substring(1);
        if(str.endsWith("/"))
            str = str.substring(0, str.length() - 1);
        return str;
    }

    /**
     * web路径追加时间
     * @param webPath
     * @param timeUnit
     * @return
     */
    public static String appendTimePath(String webPath, TimeUnit timeUnit){
        if(!webPath.endsWith("/"))
            webPath = webPath + "/";
        SimpleDateFormat format = new SimpleDateFormat(timeUnit.getFormat());
        String timePath = format.format(new Date());
        String result = webPath + timePath;
        return result;
    }

    public enum TimeUnit{
        YEAR("yyyy"),
        MONTH("yyyyMM"),
        DAY("yyyyMMdd");
        private String format;

        TimeUnit(String format){
            this.format = format;
        }
        public String getFormat(){
            return format;
        }
    }

    public static void main(String[] args) {
        String srcName = "图片.png";
        String result = appendBeforeDot(srcName, "_" + GetTimeUtil.getNowTimeStamp(), "_", RandomStringUtils.randomNumeric(4));
        System.out.println(result);

        String pathYear = "user";
        System.out.println(appendTimePath(pathYear, TimeUnit.YEAR));
        System.out.println(appendTimePath(pathYear, TimeUnit.MONTH));
        System.out.println(appendTimePath(pathYear, TimeUnit.DAY));

        String path = "/baidu/";
        System.out.println(trimSlash(path));
        System.out.println(appendWebPath(path, "/1ewe/", "chongyang/"));
        //https://img2018.cnblogs.com/blog/1478368/201911/1478368-20191103192011017-752436299.png
    }
}

日期工具类

package com.yuantiao.smartcardms.util;

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

/**
 * 时间工具类
 */
public class GetTimeUtil {
    //时间戳
    public static final String timeStamp="yyyyMMddHHmmssSSS";
    public static final String time_Stamp="yyyy-MM-dd HH:mm:ss.SSS";
    public static final String date_time="yyyy-MM-dd HH:mm:ss";

    /**
     * 获取当前时间戳--毫秒
     * @return
     */
    public static String getNowTimeStamp() {
        SimpleDateFormat sdf = new SimpleDateFormat(timeStamp);
        return sdf.format(new Date());
    }

    /**
     * DateFormatter Date to String.
     *
     * @param format
     *            日期定义格式
     * @param date
     *            Date类型日期
     * @return String类型日期
     */
    public static String format(String format, Date date) {
        try {
            if (date == null || "".equals(date)) {
                return null;
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取两个时间中的每一天
     * @param bigtimeStr 开始时间 yyyy-MM-dd
     * @param endTimeStr 结束时间 yyyy-MM-dd
     * @return
     * @throws ParseException
     */
    public static List<String> getDays(String bigtimeStr, String endTimeStr) throws ParseException {
        Date bigtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(bigtimeStr + " 00:00:00");
        Date endtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTimeStr + " 00:00:00");
        //定义一个接受时间的集合
        List<Date> lDate = new ArrayList<>();
        lDate.add(bigtime);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(bigtime);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(endtime);
        // 测试此日期是否在指定日期之后
        while (endtime.after(calBegin.getTime()))  {
            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        List<String> datas = new LinkedList<>();
        for (Date date : lDate) {
            datas.add(new SimpleDateFormat("yyyy-MM-dd").format(date));
        }
        return datas;
    }

    public static void main(String[] args) {
        String nowTimeStamp = GetTimeUtil.getNowTimeStamp();
        System.out.println(nowTimeStamp);
    }
}

文件上传服务类

package com.yuantiao.smartcardms.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @date: 2019/11/7 14:55
 */
@Service
public class FileService {

    public Map<String, String> upload(MultipartFile file, String webPath, HttpServletRequest request){
       return  upload(file.getOriginalFilename(), file, webPath, request);
    }

    public Map<String, String> upload(String fileName, MultipartFile file,String webPath, HttpServletRequest request){
        //处理后缀
        if(!webPath.endsWith("/"))
            webPath += "/";
        String webUrl = webPath + fileName;

        HashMap<String, String> result = new HashMap<>();
        //获取物理路径
        String fileRealPath = request.getServletContext().getRealPath(webUrl);
        File destFile = new File(fileRealPath);

        //目录不存在
        if(!destFile.getParentFile().exists()){
            destFile.getParentFile().mkdirs();
        }
        //目录存在是文件
        if(destFile.getParentFile().isFile()){
            result.put("flag", "fail");
            result.put("message","父级路径是文件而不是目录");
            return result;
        }
        //文件已经存在
        if(destFile.exists()){
            result.put("flag", "fail");
            result.put("message","文件已经存在");
            return result;
        }
        try {
            file.transferTo(destFile);
            result.put("flag", "success");
            result.put("message","文件上传成功");
            result.put("webUrl",webUrl);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("flag", "fail");
            result.put("message","文件写入本地发生异常");
        }
        return result;
    }
}

服务器地址

server:
  servlet:
    context-path: /mozq
String contextPath = request.getContextPath();
// /mozq

String realPath1 = request.getServletContext().getRealPath(null);
// null

String realPath2 = request.getServletContext().getRealPath("");
//C:\Users\1\AppData\Local\Temp\tomcat-docbase.1683852606771175828.80\

String realPath3 = request.getServletContext().getRealPath("/upload");
// C:\Users\1\AppData\Local\Temp\tomcat-docbase.3156895875552019719.80\upload

String realPath4 = request.getServletContext().getRealPath("download");
// C:\Users\1\AppData\Local\Temp\tomcat-docbase.3156895875552019719.80\download

文件系统路径分隔符

System.out.println(File.separator);

bugs

Caused by: java.io.FileNotFoundException: C:\Users\1\AppData\Local\Temp\tomcat-docbase.1363371158874723329.80\upload\user\Capture001changzhou.png (系统找不到指定的路径。)
Can't load log handler "java.util.logging.FileHandler"
java.nio.file.NoSuchFileException: log\spring.log.0.lck
java.nio.file.NoSuchFileException: log\spring.log.0.lck
原因:
    spring日志打印不出来,然后端口号被占用,直接启动失败没有任何提示信息。
Caused by: java.lang.IllegalArgumentException: ContextPath must start with '/' and not end with '/'
正确代码:
server:
  servlet:
    context-path: /mozq
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!