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<T> {
    //反馈给前端的信息
    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());
    }
}

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBootVue前后端分离项目中,实现文件上传回显可以通过以下步骤完成。 首先,前端部分需要创建一个文件上传的组件,可以使用Vue的axios库来发送文件到后端。在组件中,通过input标签的type属性设置为file,用户可以选择要上传的文件。然后,通过axios库将文件发送到后端的API接口。 在后端部分,需要创建一个接收文件上传的API接口。可以使用SpringBoot的MultipartFile来接收文件。在接口中,可以对文件进行处理,例如保存到服务器的指定路径下。 接下来,为了实现文件回显,可以在后端创建一个API接口,用于获取已上传的文件列表。在前端部分,可以通过axios库调用该API接口,获取文件列表,并在页面上展示出来。 需要注意的是,前后端分离的项目中,前端和后端是独立的两个部分,需要通过API接口进行通信。因此,在前端部分需要配置好API接口的地址,以便正确地发送请求和接收响应。 以上是实现SpringBootVue前后端分离文件上传回显的一般步骤。具体的实现细节可以根据项目需求进行调整和扩展。 #### 引用[.reference_title] - *1* *3* [Vue+SpringBoot实现前后端分离文件上传](https://blog.csdn.net/oppo5630/article/details/79318715)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Springboot+vue前后端分离实现文件上传](https://blog.csdn.net/qq_51742972/article/details/123705718)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值