java实现图片上传

VUE+iView 实现上传图片及反显

1、前端上传控件

<div>
	<Upload
		ref="upload"
		:show-upload-list="true"
		:on-success="handleSuccess"
		:format="['jpg','png','xlsx','docx']"
		:max-size="2048"
		:on-format-error="handleFormatError"
		:on-exceeded-size="handleMaxSize"
		multiple
		type="select"
		action="/api/wp/test/upload"
		style="display: inline-block;width:58px;">
			<div style="width: 58px;height:58px;line-height: 58px;">
			    <z-icon type="ios-camera" size="50"></z-icon>
			</div>
	</Upload>
</div>

<div class="img-modal">
  <img :src="imgUrl">
</div>

2、controller处理并返回结果

    /**
     *  上传图片、附件
     * @param file
     * @param request
     * @param response
     * @return
     */
	@RequestMapping("/upload")
    public Object uploadPicture(@RequestParam(value="file",required=false)MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        ResponseResult result = new ResponseResult();//返回结果集
        Map<String, Object> map = new HashMap<String, Object>();
        File targetFile=null;
        String url="";//返回存储路径
        int code=1;
        System.out.println(file);
        String fileName=file.getOriginalFilename();//获取文件名加后缀
        if(fileName!=null&&fileName!=""){
            String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/data/img/";//存储路径
            String path = request.getSession().getServletContext().getRealPath("data/img"); //文件存储位置
            String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
            fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名

            //先判断文件是否存在
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileAdd = sdf.format(new Date());
            //获取文件夹路径
            File file1 =new File(path+"/"+fileAdd);
            //如果文件夹不存在则创建
            if(!file1 .exists()  && !file1 .isDirectory()){
                file1 .mkdir();
            }
            //将图片存入文件夹
            targetFile = new File(file1, fileName);
            try {
                //将上传的文件写到服务器上指定的文件。
                file.transferTo(targetFile);
                url=returnUrl+fileAdd+"/"+fileName;
                System.out.println(url);
                code=0;
                result.setCode(code);
                result.setMessage("图片上传成功");
                map.put("url", url);
                result.setResult(map);
            } catch (Exception e) {
                e.printStackTrace();
                result.setMessage("系统异常,图片上传失败");
            }
        }
        return result;
    }

3、返回结果实体类

public class ResponseResult {

    private Integer code;
    private String message;
    private Map<String, Object> result;

    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }

    public Map<String, Object> getResult() {
        return result;
    }
    public void setResult(Map<String, Object> result) {
        this.result = result;
    }
}

4、前端处理返回结果并反显

<script>
export default {
	data () {
	    return {
	    	file: null,
		    loadingStatus: false,
		    imgUrl: ''
	    }
	},
	methods: {
		handleSuccess: function (res, file, fileList) {
	        this.imgUrl = res.result.url
	        this.upLoadImgModal = true
	    },
	    handleFormatError: function (file) {
      		this.$Notice.warning({
	        	title: 'The file format is incorrect',
	        	desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
      		})
    	},
    	handleMaxSize: function (file) {
	        this.$Notice.warning({
		        title: 'Exceeding file size limit',
		        desc: 'File  ' + file.name + ' is too large, no more than 2M.'
	        })
	    }
	}
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值