springboot图片上传功能实现

要想在springboot上实现图片上传功能,要做一下操作
1.创造一个配置类

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
class MyPicConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\img\\";
        //       /images/**是对应resource下工程目录
        System.out.println(path);
        registry.addResourceHandler("/img/**").addResourceLocations("file:"+path);
    }
}

其中,System.getProperty(“user.dir”)是当前的工作目录的意思,而addResourceHandler("/img/**").addResourceLocations(“file:”+path)则是为后面的目录创建了一个虚拟访问路径,我们就可以访问前面的路径可以访问图片放在tomcat里面的目录了。
2.配置yml文件

web:
  upload-path: E:\workspace\eclipse-jee-workspace\furniturepro\src\main\resources\static\img\

这个是你上传图片到本地里面的目录,如果你只把图片上传到tomcat上面的话,每当你重启项目时,上面的图片就会消失了,所以要把其上传到本地路径里面才行
在yml还要配置这样的代码

resources:
    static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}

这个配置就是当你重启项目时,他就会从本地将你的图片加载到页面上来。
接下来,我觉得最为重要的是实现类,毕竟你写好了service层的实现类后,controller层和页面也不怎么难了,下面是实现类的代码:

@Value("${web.upload-path}")
    private String uploadPath;
    @Override
    public ResponseResult doUpdateAvartar(MultipartFile file, HttpSession session) throws IOException {
        if(file==null){
            return new ResponseResult(201,"文件为空,请重新输入文件。");
        }
        if(file.getSize()>1024*1024*10){
            return new ResponseResult(202,"文件过大,请重新上传。");
        }
        String filename = file.getOriginalFilename();
        int index = filename.indexOf(".");
        String suffix =filename.substring(index);
        long time =System.currentTimeMillis();
        String newfilename = time+suffix;
        String path= session.getServletContext().getRealPath("upload");
        System.out.println(path);
        File file1 =new File(path);
        if(!file1.exists()){
            file1.mkdir();
        }
        String filePath=path+"/"+newfilename;
        /*File file2=new File(filePath);*/
        File file2=new File(uploadPath,newfilename);
        file.transferTo(file2);
        System.out.println(filePath);
        Integer userId=1;
        String userName= (String) session.getAttribute("userName");
        String imageName = "http://localhost:8088/furniture/img/"+newfilename;
        int row = userMapper.updateAvartar(newfilename,userId,userName);
        if(row!=1){
            return new ResponseResult(203,"上传图片失败");
        }
        return new ResponseResult(200,imageName);
    }

这就是我全部代码了

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Spring Boot和Vue.js来实现图片上传功能。下面是一个基本的示例: 在Spring Boot端,你可以使用`@PostMapping`注解来创建一个处理图片上传请求的控制器方法。你需要使用`MultipartFile`类型的参数来接收上传的文件。然后,你可以使用`transferTo()`方法将文件保存到服务器的指定位置。 ```java @RestController public class UploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { // 获取文件的字节数组 byte[] bytes = file.getBytes(); // 在这里处理文件保存的逻辑,比如保存到数据库或者文件系统中 return "上传成功"; } catch (IOException e) { e.printStackTrace(); return "上传失败"; } } } ``` 在Vue.js端,你可以使用`vue-axios`库来发送文件上传请求。首先,你需要引入必要的依赖和配置: ```javascript // main.js import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios) ``` 然后,在Vue组件中,你可以创建一个文件选择器,并在选择文件后将其发送到服务器: ```html <template> <div> <input type="file" @change="handleFileUpload"> <button @click="uploadFile">上传</button> </div> </template> <script> export default { data() { return { file: null } }, methods: { handleFileUpload(event) { this.file = event.target.files[0] }, uploadFile() { let formData = new FormData() formData.append('file', this.file) this.axios.post('/upload', formData) .then(response => { console.log(response.data) }) .catch(error => { console.log(error) }) } } } </script> ``` 这样,当你选择文件并点击上传按钮时,Vue组件会将文件发送到Spring Boot端的上传接口。 请注意,以上只是一个简单的示例,你可能还需要添加一些额外的逻辑来处理文件的保存、文件格式的验证等。此外,你还可以使用一些第三方库来简化文件上传的流程,比如`vue-upload-component`或`element-ui`等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值