首页 > 其他分享 >SpringBoot,Vue,ELementui实现文件上传,下载,删除

SpringBoot,Vue,ELementui实现文件上传,下载,删除

时间:2022-11-05 12:45:05浏览次数:56  
标签:Vue SpringBoot ELementui res file error put new name

SpringBoot,Vue,ELementui实现图片文件上传、下载、删除:

el-upload表单+vue

效果:

代码:

	        <el-upload
		  class="avatar-uploader"
		  action="/api/common/upload"
		  :on-preview="handlePreview"
		  :on-remove="handleRemove"
		  :before-remove="beforeRemove"
		  :on-success="success"
		  :on-error="error"
		  drag
		  :limit="3"
		  :on-exceed="handleExceed"
		  :file-list="fileList">
		    <el-image
			   v-if="url"
		      :src="url"
			  fit="cover"></el-image>
		   <i v-else class="el-icon-upload"></i>
		   <div v-show="!url" class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<!-- 		   <div slot="error" class="image-slot">
		     <i class="el-icon-picture-outline"></i>
		   </div> -->
		  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
		</el-upload> 

vue.js处理:

	export default{
		name: 'test',
		data() {
		  return {
			fileList: [],
			url: ''
		}
		},
		methods: {
		  handleRemove(file, fileList) {
			deleteFile(file.response.name).then(res=>{
				if(res.data.status == 'success'){
					this.$message.success("移除成功!")
					this.url = ""
				}
				else if(res.data.status == 'error'){
					this.$message.error("移除失败!")
				}
			}).catch(err=>{
				this.$message.error("发生错误了!"+err)
			})
		  },
		  handlePreview(file) {
			window.open("/api/common/download?name="+file.response.name)
		  },
		  handleExceed(files, fileList) {
			this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
		  },
		  beforeRemove(file, fileList) {
			return this.$confirm(`确定移除 ${ file.name }?`);
		  },
		  success(response, file, fileList){
			this.url = "/api/common/download?name="+response.name
		  	this.$message.success("文件上传成功")
		  },
		  error(){
		  	this.$message.error("文件上传失败")
		  },
		},
		created() {
			this.$store.commit('setPath', 'testPage')
		}

文件上传:

    @Value("${hi.path}")
    private String basePath;
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM-dd/");

    @PostMapping("/upload")
    public Map<String,Object> fileUpload(MultipartFile file, HttpServletRequest req){
        HashMap<String, Object> res = new HashMap<>();
        String originalFilename = file.getOriginalFilename();
        if (!(originalFilename.endsWith(".jpg") || originalFilename.endsWith(".png") || originalFilename.endsWith(".jpeg"))){
            res.put("status","error");
            res.put("msg","文件类型错误!");
        }
//        String realPath = req.getServletContext().getRealPath("images");
        File folder = new File(basePath);
        if (!folder.exists()){
            folder.mkdir();
        }
        String newName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf('.'));
        try {
            file.transferTo(new File(folder,newName));
//            String url = req.getScheme()+"://" + req.getServerName() + ":" + req.getServerPort() + "images" +newName;
//            res.put("url", url);
            res.put("status", "success");
            res.put("name", newName);
        } catch (IOException e) {
            res.put("status", "error");
            res.put("msg", e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

文件下载:

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        try {
            //输入流,通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //输出流,通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            if (name.endsWith("png")){
                response.setContentType("image/png");
            }else{
                response.setContentType("image/jpeg");
            }

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

文件删除:

    @DeleteMapping("/delete")
    public Map<String,Object> deleteFile(@RequestParam("name") String name){
        Map<String, Object> res = new HashMap<>();
        File file = new File(basePath + name);
        if (file.exists()){
            file.delete();
            res.put("status","success");
        }
        else{
            res.put("status","error");
        }
        return res;
    }

标签:Vue,SpringBoot,ELementui,res,file,error,put,new,name
From: https://www.cnblogs.com/hiworld-engineer/p/16855390.html

相关文章