springboot前后端分离,文件上传以及回显地址

这是为了记录自己项目中遇到的问题,以及解决方式

首先是 上传地址的设置

在 application.properties中设置如下

#文件上传路径
prop.upload-folder = D:/test/
#文件回显路径,也就是你需要回传给前端的路径
prop.upload.path.relative = /file/

其次在项目中 新增配置包,包名叫config(这个名字看个人喜好啊)

在config下,新增配置类如下



import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.Properties;

//必须加这个注解,否则不生效
@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {

    //根据注解读取配置文件中设置的文件上传路径
    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;
  

    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("pageSizeZero", "true");
        properties.setProperty("reasonable", "true");
        //配置mysql数据库的方言
        properties.setProperty("dialect", "mysql");
        properties.setProperty("reasonable", "true");
        pageHelper.setProperties(properties);
        return pageHelper;

    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
           //此处的意思是,当别人在请求你的文件路径 ip+端口+file/**(代表所上传的文件的时候,系    
           //统会将这个地址映射到你上传的路径 此处是 UPLOAD_FOLDER  )
        registry.addResourceHandler("/file/**").
                addResourceLocations("file:" + UPLOAD_FOLDER);
    }


}

然后编写上传控制器  FileController


import com.jk.login.info.ResultInfo;
import com.jk.login.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;

@RestController
@RequestMapping("/file")
public class FileController {


    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;
    /**显示相对地址*/
    @Value("${prop.upload.path.relative}")
    private String fileRelativePath;

    @RequestMapping(value = "/upload")
    public ResultInfo upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        ResultInfo result = new ResultInfo();
        if (file == null) {
            result.setMsg("上传失败,文件为空");
            result.setSuccess(false);
            return result;
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        String savePath = UPLOAD_FOLDER;
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录,则创建目录
            savePathFile.mkdir();
        }
        //通过UUID生成唯一文件名
        String filename = UUIDUtils.getUUID()+ "." + suffix;
        try {
            //将文件保存指定目录
            file.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("上传失败");
            result.setSuccess(false);
            return result;
        }
         //request.getSchema() 可以返回当前页面使用的协议,http 或是 https;
         //request.getServerName() 可以返回当前页面所在的服务器的名字;
         //request.getServerPort() 可以返回当前页面所在的服务器使用的端口,就是80;
         //request.getContextPath() 可以返回当前页面所在的应用的名字;
         //此处返回的路径为  
         //http://192.168.50.108:8080/file/1c49bcace6b14ed7b00f8c544481f095.jpg

        String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + fileRelativePath + filename;
        result.setMsg("上传成功");
        result.setSuccess(true);
        result.setDetail(url);
        return result;
    }


}

 前端信息返回类如下


public class ResultInfo {
    //反馈给前端的信息
    private String msg;
    //请求状态信息
    private Boolean success = false;
    //返回具体的数据
    private T detail = null;

    @Override
    public String toString() {
        return "ResultInfo{" +
                "msg='" + msg + '\'' +
                ", success=" + success +
                ", detail=" + detail +
                '}';
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public T getDetail() {
        return detail;
    }

    public void setDetail(T detail) {
        this.detail = detail;
    }
}

UUid工具类如下,或者自己找一个网上很多

import java.util.UUID;

public class UUIDUtils {

    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static void main(String[] args) {
        System.out.println("格式前的UUID : " + UUID.randomUUID().toString());
        System.out.println("格式化后的UUID :" + getUUID());
    }
}

 

你可能感兴趣的:(spring,boot,vue)