精华内容
下载资源
问答
  • 在实际开发中会遇到一些图片上传的问题,避免采坑,拿走直接用 <template> <div> <div>导入并预览</div> <el-upload class="upload-demo" action=...

    在实际开发中会遇到一些图片上传的问题,避免采坑,拿走直接用

    <template>
        <div>
            <div>导入并预览</div>
             <el-upload
                      class="upload-demo"
                      action="https://jsonplaceholder.typicode.com/posts/"   //上传路径 
                      :on-change="handleChange"
                       :show-file-list="false"
                      style="margin-left: 5px; display:inline;font-size:14px;"
                      accept="image/*"   //上传格式
                      :auto-upload="false"
                      :before-upload = "beforeAvatarUpload">
                  <el-button size="medium" type="primary" style="margin-top: 5px;margin-bottom: 5px;">导入</el-button>
             </el-upload>
             <div v-for="(item,index) in fileList" style="position: relative;">
                <img :src="item" class="avatar">
                <span class="spanname" >
                  <span @click="handelchange(item)" style="cursor: pointer;">
                    <i class="el-icon-zoom-in" style="font-size:20px"></i>
                  </span>
                  <span style="cursor: pointer;" @click="removeimg(item)">
                    <i class="el-icon-delete" style="font-size:20px"></i>
                  </span>
                </span>
             </div>
             <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
        </div>
    </template>
    <script>
    export default {
        data(){
            return{
              dialogVisible:false,
                fileList:[],
                imageUrl:'',
                dialogImageUrl:''  //图片预览路径
            }
        },
         methods: {
           handleChange(file,fileList,params){
             var testmsg = /^image\/(jpeg|png|jpg)$/.test(file.raw.type)
            //  console.log(testmsg)
              const isLt5M = file.size / 1024 / 1024 < 5
              if (testmsg !=true) {
                this.$message.error('上传图片格式不对!')
                return
              }
              if (!isLt5M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
              }
            
             this.imageUrl=URL.createObjectURL(file.raw)
             this.fileList.push(this.imageUrl)
                },
           beforeAvatarUpload(file) {
              var testmsg = /^image\/(jpeg|png|jpg)$/.test(file.type)
              const isLt5M = file.size / 1024 / 1024 < 5
              if (!testmsg) {
                this.$message.error('上传图片格式不对!')
                return
              }
              if (!isLt5M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
              }
              return testmsg && isLt5M
            },
            handelchange(file){
              console.log(file)
              this.dialogVisible =true
              this.dialogImageUrl = file
            },
            removeimg(item, fileList){
              this.rrrrrr(item,this.fileList)
            },
            rrrrrr(arr,item){
              var index = item.indexOf(arr)
              console.log(index)
              item.splice(index,1)
            },
        }
    }
    </script>
    <style >
    .el-upload-list__item-name{
      display: none;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
      .spanname{
        width: 100px;
        height: 30px;
        /* background: blue; */
        position: absolute;
        top: 75px;
        left: 40px;
      }
    </style>
    
    展开全文
  • vue上传下载图片

    2020-01-10 21:44:42
    //这是第一种上传图片的方法 <el-form-item label="风景"> <el-upload class="upload-demo" action="http://localhost:9083/student/uploadPhoto" :headers="head...
    //这是第一种上传图片的方法 只能上传单张图片
            <el-form-item label="风景">
              <el-upload
                class="upload-demo"
                action="http://localhost:9083/student/uploadPhoto"
                :headers="headers"
                list-type="picture"
              >
    		<el-button size="small" type="primary">点击上传</el-button>
    	</el-upload>
    </el-form-item>
    
    //这是第二种上传图片的方法  可以放在form表单中
     <el-form>
              <input class="file" type="file" title="请选择文件" value="请选择文件" />
     </el-form>
    
    
    export default {
      data() {
        return {
           headers: {
              "Access-Control-Allow-Origin": "http://127.0.0.1:9083"
            },
           fileList: [{}],
           formcity:{}
       }, saveStudent() {
       //new一个formData对象因为图片的格式需要转换
          let formData = new FormData();
          formData.append(
            "photo",
            document.querySelector("input[type=file]").files[0]
          );
          //后台是用photo这个属性名接的
    
          for (var obj in this.formcity) {
            formData.append(obj, this.formcity[obj]);
          }
          //通过遍历form表单的对象来把form中的每个属性放到new的对象当中
    
          axios({
            url: "http://localhost:9083/student/save",
            data: formData,
            method: "post",
            headers: {
              "Content-Type": "multipart/form-mixed",
              "Access-Control-Allow-Origin": "http://127.0.0.1:9083"
            }
          })
            .then(res => {
              console.log(res.data);
            })
            .catch(e => {
              console.log(e);
            }); // 发送请求
        }
    
    }
    
    
    
    
    
    
       //从配置文件中取出存储照片的磁盘
        @Value("${upload.rootDir}")
        private String uploadRootDir;
        
    //这个方法是用来接收第一种方法上传图片的:具体如下
        @RequestMapping("/student/uploadPhoto")
        public Map<String, Object> uploadPhoto(@RequestParam(required = false, name = "file") MultipartFile file) 			     throws IOException {
           upload(file); //调用自己的工具类保存
    		
            //返回类型无所谓
            return null;
        }
    
    //这个类是用于第二种方法 添加整个对象时如添加学生
        @RequestMapping("/student/save")
        public Map<String, Object> save(Student student, City city, @RequestParam(required = false, name = "photo") MultipartFile photo) throws IOException {
            FileInfo fileInfo = upload(photo);//调用自己的工具类保存
            
            city.setCityScenery(fileInfo.getPath());
           //fileInfo.getPath()是在工具类中存好的照片路径
            int insertcity = cityApi.insertcity(city); //调用添加的方法存到数据库
            return Collections.singletonMap("error", false);
    
        }
    
        private FileInfo upload(MultipartFile photo) throws IOException {
            String originalFilename = photo.getOriginalFilename(); // te.st.gif 获取文件名
            String extension = getExtension(originalFilename); //去掉后缀名
            String fileName = UUID.randomUUID().toString() + extension; // UUID.gif
            String filePath = "/photo/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + fileName;
            long size = photo.getSize();
    		//保存的格式为photo文件夹/日期文件夹/照片                这样方便查看
    		
            //FileInfo是自己创建的类 下面有详细介绍
            FileInfo fileInfo = new FileInfo();
            fileInfo.setName(fileName);
            fileInfo.setOriginalName(originalFilename);
            fileInfo.setSize(size);
            fileInfo.setPath(filePath);
    
    //        uploadRootDir是磁盘路径
            String absolutePath = uploadRootDir + filePath;
    
            File file = new File(absolutePath);
            file.getParentFile().mkdirs(); //创建文件夹
    
            photo.transferTo(file);  //保存文件
            System.out.println("存储的路径是" + fileInfo);
            return fileInfo;
        }
    
        //    这个方法是去掉后缀名
        private String getExtension(String originalFilename) {
            String extension = "";
            int index = originalFilename.lastIndexOf('.');
            if (index != -1) {
                extension = originalFilename.substring(index); // .gif
            }
            return extension;
        }
    

    上面的FileInfo是自己创建的类

    @Data
    public class FileInfo {
        private Integer id;
        private String originalName;
        private String name;
        private Long size;
        private String path;
    }
    

    下面是配置文件

    #这里用的是application.properties
    upload.rootDir=E:\\upload
    

    这就是保存的案例
    数据库中存的路径是\photo\20200105\be88f452-be9e-4893-8359-b4be636e49d4.jpg
    在这里插入图片描述

    如何展示图片

      <el-table-column label="图片">
         <template slot-scope="scope">
           <img :src="'http://localhost:9083/showImg?pathName='+scope.row.cityScenery" />
         </template>
      </el-table-column>
    //之前保存的路径存到了cityScenery
    //展示的时候需要到后台io流处理一下所以写了一个请求的语句
    

    //这个方法的路径就是 localhost:9083/showImg

    //这里依然是读取配置文件中的磁盘路径
       @Value("${upload.rootDir}")
        private String uploadRootDir;
    
        @RequestMapping(value = "/showImg")
        @ResponseBody
        public void showImg(HttpServletRequest request, HttpServletResponse response, String pathName) {
        //IO流读取就是之前学过的知识这里不过太多解释
            File imgFile = new File(uploadRootDir+pathName);
            FileInputStream fin = null;
            OutputStream output = null;
            try {
                output = response.getOutputStream();
                fin = new FileInputStream(imgFile);
                byte[] arr = new byte[1024 * 10];
                int n;
                while ((n = fin.read(arr)) != -1) {
                    output.write(arr, 0, n);
                }
                output.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

    下面是配置文件

    #这里用的是application.properties
    upload.rootDir=E:\\upload
    

    以上就是上传图片的基本技术,有报错的可联系本人,共同进步.

    代码千万行,注视第一行。格式不规范,报错两行泪!~

    展开全文
  • 项目要求:从前端把用户的图片/文件上传到后端存到服务器中,及从服务器中下载相应的图片/文件。 由于springboot的Tomcat是内置的,不容易配置,且若采用后端提供url来下载文件,很可能要面对不好解决的跨域问题。 ...

    前言

    项目要求:从前端把用户的图片/文件上传到后端存到服务器中,及从服务器中下载相应的图片/文件。

    由于springboot的Tomcat是内置的,不容易配置,且若采用后端提供url来下载文件,很可能要面对不好解决的跨域问题。

    故本文章采用的把文件流放在http请求的body中的方式,使得文件能够在vue前端和spring后端间传输。

    并通过简单的方式解决了 下载后的文件乱码/损坏 问题。

    后端Springboot

    ImageController

    @RestController
    @RequestMapping("api")
    public class ImageController {
        @Autowired
        private ImageService imageService;
        private String uuidName;
    
        @PostMapping(value = "/image/upload")
        public ResponseEntity upload(@RequestParam("file") MultipartFile uploadFile){
            uuidName = UUID.randomUUID().toString();
            String fileName = uploadFile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            uuidName += suffix;
    
            imageService.saveImage(uuidName, uploadFile);
            return new ResponseEntity(HttpStatus.CREATED);
        }
    
        @PostMapping(value = "/image/export")
        public ResponseEntity export(@Validated @RequestBody String fileName){
            return imageService.exportImage(fileName);
        }
    
        @DeleteMapping(value = "/image/{id}")
        public ResponseEntity delete(@PathVariable Integer id, @Validated @RequestBody String fileName){
            imageService.delete(id, fileName);
            return new ResponseEntity(HttpStatus.OK);
        }
    }
    

    ImageService

    public interface ImageService {
    
        /**
         * delete
         * @param id
         * @param fileName
         */
        //@CacheEvict(allEntries = true)
        void delete(Integer id, String fileName);
    
        /**
         * saveImage
         * @param uuidName 通过UUID重新命名
         * @param uploadFile 图片文件
         */
        void saveImage(String uuidName, MultipartFile uploadFile);
    
        /**
         * exportImage
         * @param fileName
         * @return
         */
        ResponseEntity exportImage(String fileName);
    }
    

    ImageServiceImpl

    public class ImageServiceImpl implements ImageService {
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void delete(Integer id, String fileName) {
            String deleteFilePath = ImageConstants.AGREEMENT_FOLDER + fileName;
            try {
                FileUtils.deleteFile(new File(deleteFilePath));
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    
        @Override
        public void saveImage(String uuidName, MultipartFile uploadFile){
            String uploadPath = ImageConstants.AGREEMENT_FOLDER;
    
            // 如果目录不存在则创建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            /*
            // 获取源文件名
            String fileName = uploadFile.getOriginalFilename();
    //        //获取源文件名
    //        String originalFileName = fileName.substring(0, fileName.lastIndexOf("."));
            // 获取源文件名后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            */
            File file = new File(uploadPath, uuidName);
            try {
                uploadFile.transferTo(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        public ResponseEntity exportImage(String fileName){
            String exportPath = ImageConstants.AGREEMENT_FOLDER + fileName;
            try {
                File file = new File(exportPath);
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Disposition", "attachment; filename=" + fileName);
                headers.add("Content-Length", String.valueOf(file.length()));
                return  ResponseEntity
                        .ok()
                        .headers(headers)
                        .contentLength(file.length())
                        .contentType(MediaType.parseMediaType("application/octet-stream"))
                        .body(new FileSystemResource(file));
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
            }
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
    }
    

    ImageConstants

    public interface ImageConstants {
    
        /** 存储目录名称 */
        public static final String AGREEMENT_FOLDER_NAME = "_image";
        /** 存储目录 */
        public static final String AGREEMENT_FOLDER = Constants.ROOT_FOLDER + AGREEMENT_FOLDER_NAME + File.separator;
    
    }
    

    FileUtils

    public class FileUtils {
        /**
         * 递归删除文件
         * @param file
         */
        public static void deleteFile(File file) {
            // 判断是否是一个目录, 不是的话跳过, 直接删除; 如果是一个目录, 先将其内容清空.
            if(file.isDirectory()) {
                // 获取子文件/目录
                File[] subFiles = file.listFiles();
                // 遍历该目录
                for (File subFile : subFiles) {
                    // 递归调用删除该文件: 如果这是一个空目录或文件, 一次递归就可删除.
                    // 如果这是一个非空目录, 多次递归清空其内容后再删除
                    deleteFile(subFile);
                }
            }
            // 删除空目录或文件
            file.delete();
        }
    }
    

    前端Vue

    image.vue

    <!-- 上传图片 -->
    <el-upload
      ref="upload"
      :multiple="false"
      :file-list="fileList"
      :auto-upload="false"
      :limit="1"
      :http-request="importConfirm"
      :before-upload="beforeUpload"
      action
      accept=".jpeg, .jpg, .png"
    >
      <el-button slot="trigger" size="small" type="primary" plain>选取文件</el-button>
      <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          plain
          @click="submitUpload"
      >上传到服务器</el-button>-->
      <div
         slot="tip"
         class="el-upload__tip"
      >注意:只能上传jpeg/png文件,且文件大小不能超过{{ fileSizeLimit }}MB
      </div>
    </el-upload>
    
    <!-- 显示图片 -->
    <div v-show="isShow" style="margin: 20px auto">
      <p>{{ imageName }}</p>
      <el-image :src="imageLink" />
    </div>
    
    <script>
    import { del, upload, download } from '@/api/image'
    export default {
      data() {
        return {
          delLoading: false, isShow: false,
          imageLink: '', imageName: '',
        }
      },
      created() {
        // 略
      },
      methods: {
        // 上传的文件格式、大小限制
        beforeUpload(file) {
          var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
          const extension0 = testmsg === 'jpeg'
          const extension1 = testmsg === 'jpg'
          const extension2 = testmsg === 'png'
          const isLt2M = file.size / 1024 / 1024 < this.fileSizeLimit
          if (!extension0 && !extension1 && !extension2) {
            this.$notify({
              message: '上传的文件只能是jpeg、jpg、png格式!',
              type: 'warning',
              duration: 2500
            })
            this.loading = false
            return
          }
          if (!isLt2M) {
            this.$message({
              message: '上传文件大小不能超过 ' + this.fileSizeLimit + 'MB!',
              type: 'warning'
            });
          }
          return (extension0 || extension1 || extension2) && isLt2M
        },
        // 文件上传
    	importConfirm(item) {
          const fileObj = item.file
          const formData = new FormData()
          formData.append('file', fileObj)
          upload(formData).then(res => {
            this.$notify({
              title: '文件上传成功',
              type: 'success',
              duration: 2500
            })
          }).catch(err => {
            this.loading = false
            console.log(err.response.data.message)
          })
        },
        submitUpload(){
          this.$refs.upload.submit() // 会去执行 importConfirm
        },
        // 图片文件下载
        download(filePath) {
          download(filePath).then(response => {
            const data = response
            if (!data) {
              return
            }
            const blob = new Blob([data])
            if (window.navigator.msSaveOrOpenBlob) { // 兼容IE10
              navigator.msSaveBlob(blob, filePath)
            } else { // 其他非IE内核支持H5的浏览器
              const url = window.URL.createObjectURL(blob)
              const link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', filePath)
              document.body.appendChild(link)
              link.click()
            }
          }).catch(function (error) {
            console.log(error)
          })
        },
        // 图片文件显示
        show(fileName, filePath) {
          download(filePath).then(response => {
            const data = response
            if (!data) {
              return
            }
            const blob = new Blob([data])
            this.imageName = fileName
            this.imageLink = window.URL.createObjectURL(blob)
            this.isShow = true
          }).catch(function (error) {
            console.log(error)
          })
        }
      }
    }
    </script>
    

    image.js

    // 封装好的axios请求
    import request from '@/utils/request'
    
    export function del(id, data) {
      return request({
        url: 'api/image/' + id,
        method: 'delete',
        data
      })
    }
    
    export function upload(data) {
      return request({
        url: 'api/image/upload',
        method: 'post',
        data
      })
    }
    
    export function download(data) {
      return request({
        url: 'api/image/export',
        method: 'post',
        responseType: 'arraybuffer', // 解决下载后的文件乱码/损坏问题
        data
      })
    }
    
    
    展开全文
  • vue图片上传及压缩组件的封装 源码地址 使用方法: 先去上面的链接把组件,复制到自己的components文件夹内 1.先下载 cnpm install compressorjs --save-dev //压缩 2.引入组件 <script> import upload...

    vue图片上传及压缩组件的封装

    源码地址

    使用方法:

    先去上面的链接把组件,复制到自己的components文件夹内

    1.先下载
    cnpm install compressorjs --save-dev //压缩
    
    2.引入组件
    <script>
    import uploadPictures from "../../components/uploadPictures";
    export default {
      components: {
        uploadPictures
      },
    },
    </script>
    
    3.用法
    //emitType:自定义方法,接收从后端返回的图片码
    //title:名字,身份证上传、银行卡上传,(需要则传、不需要不传)
    <uploadPictures :openTitle="{emitType:'idCard',title:$t('m.openingInformation.HKPic')}"/>
    
    //在mounted里面监听后端返回的码
     mounted() {
        this.judgeLogin();
          this.$on('idCard',msg=>{
          console.log(msg)
        })
           this.$on('addressCard',msg=>{
          console.log(msg)
        })
      }
    
    展开全文
  • js+css实现手机端的多图片上传,为了方便使用,css和js都未内联,为性能建议使用时改为外联; 如要用到pc端,直接去掉px转换为rem的js代码,修改单位即可; 因multiple在安卓手机中不兼容,所以在安卓上只能一次选中...
  • base64编码上传图片 <input type="file" id="id" name="imageOne" @change="imageOne" accept="image/jpg, image/jpeg, image/png" /> 设置input标签的type属性为file imageOne() { let files = ...
  • 最近看了一篇用 Angular4+ 写的添加水印功能,觉得挺好玩,就自己试着用 vue 写一个相同功能 效果 LIVE ☀️???????????? 在线例子 ????????☃️❄️ 代码 ✈️✈️✈️✈️✈️✈️ 直达完整代码 ????✈️????????...
  • 图片上传 前台代码 上传图片表单部分 <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body> <el-form ref="form" :model="form" :rules="rules" label-width="80px" enctype=...
  • 前端上传图片下载 通过后端接口上传图片 上传 file 对象给接口 <input type="file" ref="fileinput" name="fileContent" @input="getinfo($event)" style="display:none"> <img src="" ref="imagesss...
  • 图片上传: html部分 <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update($event)"/> axios的post请求,发送form数据部分,这样就可以无刷新的提交...
  • vue 新建js文件 let OSS = require('ali-oss'); //npm 下载ali-oss let client = new OSS({ /*需要自己去申请*/ accessKeyId: '', accessKeySecret: '', bucket: '', region: '', }); export async ...

空空如也

空空如也

1 2 3 4 5 ... 17
收藏数 327
精华内容 130
关键字:

vue图片上传下载

vue 订阅