Vue【七】实现图片上传与预览-后台代码

package com.wang.wangblog.controller.admin;

import com.wang.wangblog.config.Constants;
import com.wang.wangblog.model.Vo.Result;
import com.wang.wangblog.utils.MyBlogUtils;
import com.wang.wangblog.utils.ResultGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Controller
@RequestMapping("/admin")
public class UploadController {

    @Value("${upload.path:E:\\imgs}")
    private String path;


    @PostMapping({"/upload/file"})
    @ResponseBody
    public Result upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        String month = new SimpleDateFormat("yyyyMM").format(new Date()) + File.separator;
        String destPath =  path + month;
        File fileDirectory = new File(destPath);
        //创建文件
        File destFile = new File(destPath + newFileName);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    throw new IOException("文件夹创建失败,路径为:" + fileDirectory);
                }
            }
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Result result = ResultGenerator.genSuccessResult();
        result.setData(MyBlogUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/upload/" +month+ newFileName);
        return result;
    }

}

上一篇:C语言经典例题(11) --- 序列中整数去重、班级成绩输入输出、序列重组矩阵、矩阵相等判断、矩阵转置


下一篇:在idea中如何使用Git做开发