栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

wx小程序上传图片到服务器,预览,下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

wx小程序上传图片到服务器,预览,下载

小程序代码

index.wxml

	
        
    

index.js

/上传图片
    // 上传照片
    upload: function () {
        //选择图片
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: function (res) {
                wx.showLoading({
                    title: '上传中',
                })
                //获取图片临时地址
                const filePath = res.tempFilePaths[0]
                // 自定义云端的图片名称
                const fileName = Math.floor(Math.random() * 1000000) + filePath.match(/.[^.]+?$/)[0]
                console.log(fileName);
                // 上传到服务器存储空间
                var uploadTask=wx.uploadFile({
                    url: 'http://localhost:8080/imgUpload?fileName='+fileName,
                    header: { 
                      "Content-Type": "multipart/form-data" },//类型
                     filePath: filePath,
                     name: 'file',//和后台接收的参数名字一致
                     success:(res)=>{
                       console.log(res.data);
                       wx.showToast({
                         title: '上传成功'
                       })
                     },
                     fail:function(res){
                      console.log("错误"+res);
                    }
                   })
                   uploadTask.onProgressUpdate((res)=>{
                     console.log('上传进度',res.progress);
                     console.log('已经上传的数据长度',res.totalBytesSent);
                     console.log('预期需要上传的数据总长度',res.totalBytesExpectedToSend);
                   }
            },
            fail: e => {
                console.error(e)
            },
            complete: () => {
                wx.hideLoading()
            }
        })
    },

springboot
controller层代码

package com.wx.wdcysh.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class imgUploadController {
    @ResponseBody
    @RequestMapping("/imgUpload")
    public String imgUpload(@RequestParam("file")MultipartFile file,
                            @RequestParam(name = "fileName",required=false) String fileName) throws IOException {
        //filename是前台传参时的文件名字,也可以不指定
        //不指定名字,保存时使用file.getOriginalFilename()得到文件名字;
        //保存到文件服务器
        file.transferTo(new File("E:\IdeaProjects\wdcysh\src\main\resources\static\file\"+fileName));
        System.out.println("接收到文件");
        return "上传文件成功";
    }
}


比如我设置的文件保存目录为,这是springBoot的静态资源保存位置,设置这个目录话,下载文件的时候,直接指定这个目录下的文件名字,如下载时候的url可指定为,可以不用再写下载文件的控制层了。

http://localhost:8080/file/792928.png


这时还没有连接数据库,运行报错

将springboot启动类注解改为
*(后面我有业务要连接MySQL,又报错没有自动配置注解扫描不到,启动类注解又改回来后,一切正常,图片还是可以上传也没报上面的错,所以这注解是当你没有连接数据库时加的) *

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//排除自动配置

可以成功上传,但是访问上传的图片需要重新启动springboot
出现原因
这样导致的原理是服务器的保护措施导致的,服务器不能对外部暴露真实的资源路径,需要配置虚拟路径映射访问
解决办法加配置类

package com.wx.wdcysh.config;

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

@Configuration
public class webConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("配置文件已经生效");
        //关于图片上传后需要重启服务器才能刷新图片
        //这是一种保护机制,为了防止绝对路径被看出来,目录结构暴露
        //解决方法:将虚拟路径/images/
        //        向绝对路径 (E:IdeaProjectswdcyshsrcmainresourcesstaticfile)映射

        String path="E:\IdeaProjects\wdcysh\src\main\resources\static\file\";
        registry.addResourceHandler("/file/**").addResourceLocations("file:"+path);
    }
}

此时上传完即可访问,不用重启动。
小程序图片下载





data: {
    isDownload:false
  },
  downlaod:function(){
    console.log("下载");
    var that=this;
      var downTask=wx.downloadFile({
      url: 'http://localhost:8080/file/要下载的文件名字',
     success:function(res){
       if(res.statusCode===200){
         let src=res.tempFilePath;
         that.setData({
           src:src,
           isDownload:true
         })
       }
     },
     fail:function(res){
       console.log("下载失败!"+res);
     }
     
    })
    downTask.onProgressUpdate((res)=>{
       console.log('下载进度',res.progress);
       console.log('已经下载的总数据长度',res.totalBytesWritten);
       console.log('预期需要下载的数据长度',res.totalBytesExpectedToWrite);
    })
  },

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/306092.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号