SpringBoot+小程序实现文件上传

前言

这里我并没有使用一些oss、七牛云等服务器上传文件,而是采用的本地文件上传,具体代码如下:

后端

1、POM文件

    <parent>
        <artifactId>shangyou-parent</artifactId>
        <groupId>com.cluck.video</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
   
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
       
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
    </dependencies>

2、application.yml文件

upload:
  file-space: E:\code\My Code\app\upload ###你自己想存放的文件路径

3、servie层

    /** 文件上传父目录 */
    @Value("${upload.file-space}")
    private String fileSpace;
    @Override
    @Transactional
    public ResponseVo uploadFace(String userId, MultipartFile[] files) throws IOException {
        String token = redisTemplate.opsForValue().get(USER_REDIS_SESSION + ":" + userId);
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(userId)) {
            return ResponseVo.error("用户id不能为空");
        }
        //数据库相对路径
        String uploadPathDB = "/" + userId + "/face";

        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        String imageName = UUID.randomUUID().toString();

        try {
            if (files != null && files.length > 0) {
                //文件名称
                String fileName = files[0].getOriginalFilename();
                fileName = imageName + (fileName.substring(fileName.lastIndexOf(".")));
                System.out.println("文件名称:" + fileName);
                if (StringUtil.isNotEmpty(fileName)) {
                    //最终路径
                    String filePathFace = fileSpace + uploadPathDB + "/" + fileName;
                    System.out.println(filePathFace);
                    //数据库保存路径
                    uploadPathDB += ("/" + fileName);

                    File file = new File(filePathFace);
                    if (file.getParentFile() != null || file.getParentFile().isDirectory()) {
                        //创建父文件夹
                        file.getParentFile().mkdirs();
                    }

                    outputStream = new FileOutputStream(file);
                    inputStream = files[0].getInputStream();

                    IOUtils.copy(inputStream, outputStream);
                }
            } else {
                return ResponseVo.error("上传失败~");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        }

        //TODO这里你可以把图片地址保存到数据库等等
       
        return ResponseVo.success(uploadPathDB);
    }

4、Controller层

    @PostMapping("/uploadFace")
    public ResponseVo uploadFace(String userId,
                                 @RequestParam("file")MultipartFile[] files) throws IOException {

        return usersService.uploadFace(userId, files);
    }

5.配置类

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /** 文件上传父目录 */
    @Value("${upload.file-space}")
    private String fileSpace;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("file:" + fileSpace + "/");
    }
}

后端代码主要是想从前端接收到用户id,然后把用户id当成每个用户的文件目录,
类似于E:\code\My Code\app\upload\557a99f2-48d0-4bb0-b076-8f950a3e042b\face
然后你就可以通过http://127.0.0.1:8080/557a99f2-48d0-4bb0-b076-8f950a3e042b\face\1.jpg访问图片了

小程序端代码

1、app.js

App({
  serverUrl: "http://127.0.0.1:8080",
  userInfo: null
})

2、upload.wxml

<image src="{{faceUrl}}" class="face" bindtap='changeFace'></image>

3、upload.js

const app = getApp()
Page({
  faceUrl: '../resource/image/1.jpg', //默认图片地址
}),
//上传文件
changeFace:function() {
    //获取全局变量
    var me = this;

    wx.chooseImage({//选择文件
      success (res) {
        const tempFilePaths = res.tempFilePaths
        wx.showLoading({
          title: '上传中...',
        })

        var user = app.userInfo
        var serverUrl = app.serverUrl
        //校验用户id和图片
        if(user.id == null || tempFilePaths[0].length <= 0) {
          wx.showToast({
            title: '用户id或图片不存在~',
          })
        }
        wx.uploadFile({//文件上传
          url: serverUrl +'/user/uploadFace?userId=' + user.id,  //后端请求路径
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'content-type': 'application/json'
          },
          success (res){
            
           var data = JSON.parse(res.data);
           if(data.status == 0) {
             wx.hideLoading();
             wx.showToast({
               title: '头像上传成功',
               icon: 'success',
               duration: 1500
             })
            
             me.setData({ // 设置图片
              faceUrl: serverUrl + data.msg
             })
           }
          }
        })

前端也都比较简单,主要都是参考的api文档那里也有具体示例,需要注意的就是文件上传后success回调函数里data是个字符串,你需要把它转为json也就是var data = JSON.parse(res.data);不然会出现undefined

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。