微信小程序 springboot nginx 做图片存储 上传 浏览

微信小程序前端-springboot后端-nginx图片存储

前言

本人小白一名,这是第一次学习微信小程序,特此做个记录。

首先准备nginx做图片存储

选择一个地址存放图片

#我的地址

[root@VM_0_16_centos images]# pwd
/home/photos/images
[root@VM_0_16_centos images]#

然后配置nginx

#编辑配置文件

vi nginx.conf

#加上这个
location /images/ {
    root  /home/photos/;
    autoindex on;   #打开目录浏览功能,打开就可以从浏览器访问你的images目录了,注意,不打开也能访问你的图片
}

测试:ip:port/images/images_name.扩展名

然后做springboot文件上传

代码

@RestController
@Slf4j
@Api(tags = "图片上传控制器")
public class UploadLoadController {

    @Value(value = "${file.path}")
    private String filePath;

    @PostMapping(value = "/upload")
    @ApiOperation(value = "上传文件")
    public String uploadPhoto(MultipartFile files) throws IOException {
        // 获取文件名称
        String fileName = files.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = UUID.randomUUID()+suffixName;
        byte[] bytes = files.getBytes();
        Path path = Paths.get(filePath + fileName);
        Files.write(path,bytes);
        return fileName;
    }
}

配置文件

file.path=/home/photos/images/

最后弄小程序

 wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths[0]
        console.log("路径" + tempFilePaths)
        wx.uploadFile({
         url: 'http://ip:port/jt/upload',
          filePath: tempFilePaths,
          name: 'files',
          header: {
            'content-type': 'multipart/form-data'
          },
          success(res) {
            console.log(res.data)
          }
        })
  
      }
    })

最后浏览

浏览的地址就是ip:port/images/image_name.扩展名