今天用elementUI写了一个vue的上传,本来很简单的一个事情,结果因为一个坑,用了我将近一个下午。好气哦!
记录一下吧。
我遇到的坑是,elementUI中,自带的方法中的file,并不是指图片本身,而是他的一个dom。如果要是拿他的图片,就要用file.raw。
主要是不太懂slot的用法,回头再去学习一下。
先把前后端的代码贴上:
前端:

<template>
  <div class="upload">
	<el-upload
	  action="#"
	  list-type="picture-card"
	  :auto-upload="false">
	    <i slot="default" class="el-icon-plus"></i>
	    <div slot="file" slot-scope="{file}">
	      <img
	        class="el-upload-list__item-thumbnail"
	        :src="file.url" alt=""
	      >
	      <span class="el-upload-list__item-actions">
	        <span
	          class="el-upload-list__item-preview"
	          @click="handlePictureCardPreview(file)"
	        >
	          <i class="el-icon-zoom-in"></i>
	        </span>
	        <span
	          v-if="!disabled"
	          class="el-upload-list__item-delete"
	          @click="handleUpload(file)"
	        >
	          <i class="el-icon-upload"></i>
	        </span>
	        <span
	          v-if="!disabled"
	          class="el-upload-list__item-delete"
	          @click="handleRemove(file)"
	        >
	          <i class="el-icon-delete"></i>
	        </span>
	      </span>
	    </div>
	</el-upload>
	<el-dialog :visible.sync="dialogVisible">
	  <img width="100%" :src="dialogImageUrl" alt="">
	</el-dialog>
  </div>
</template>

<script>
	import Vue from 'vue'
  export default {
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false
      };
    },
    methods: {
      handleRemove(file) {
        console.log(file);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleUpload(file) {
		let formData = new FormData();
		console.log(file.raw);
		formData.append('mpf',file.raw);
		formData.append('uid',10);

		Vue.axios.post("http://localhost:8080/ajax-server/ul", formData,{
			headers:{
				'Content-Type': 'multipart/form-data',
			}
		});
		
      }
    }
  }
</script>

后端:

@Controller
public class UploadController {
	
	@ResponseBody
	@RequestMapping("/ul1")
	public Object upload(@RequestParam("uid") String userid,MultipartFile mpf,HttpServletRequest request) {
		System.out.println(mpf);
		
		String saveFileName = UUID.randomUUID().toString().replaceAll("-", "")+"_"+mpf.getOriginalFilename();
		String filePath = request.getServletContext().getRealPath("upload")+"\\"+saveFileName;
		System.out.println(filePath);
		File f = new File(filePath);
		System.out.println(f.exists());
		try {
			mpf.transferTo(f);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(f.exists());
		System.out.println("userid:"+userid);
		return null;
	}
	
}
Logo

前往低代码交流专区

更多推荐