使用layui上传图片前后端代码

使用layui上传图片前后端代码

一、form表单里的代码


 <div class="layui-form-item">
	    <label class="layui-form-label">公司Logo</label>
	    <div class="layui-input-inline uploadHeadImage">
	        <div class="layui-upload-drag" id="headImg">
	            <i class="layui-icon"></i>
	            <p>点击上传图片,或将图片拖拽到此处</p>
	        </div>
	    </div>
	      <!--   隐藏的图片路径 -->
	    <input type="text" name="companyImg" id="companyImg" lay-verify="title" class="layui-input layui-hide">
	          
	    <div class="layui-input-inline">
	        <div class="layui-upload-list">
	            <img class="layui-upload-img headImage"  src="http://t.cn/RCzsdCq" id="demo" style="height:130px;width:130px;">
	            <p id="demoText"></p>
	        </div>
	    </div>
</div>

二、js中layui提交的图片的代码

layui.use(['form','laydate',"upload","jquery","layer", "element"], function(){
     
	var $ = layui.$,
    element = layui.element,
    layer = layui.layer,
    upload = layui.upload,
    form = layui.form,
	laydate = layui.laydate;
	laydate.render({
      //创建时间
        elem: '#date'
        });
	//单图片上传(公司logo)
    var uploadInst = upload.render({
     
        elem: '#headImg'
        , url: '${pageContext.request.contextPath }/upload/headImg'
        , size: 500
        , before: function (obj) {
     
            //预读本地文件示例,不支持ie8
            obj.preview(function (index, file, result) {
     
                $('#demo').attr('src', result); //图片链接(base64)
                var demoText = $('#demoText');
                demoText.html('预览图片!!!');
            });
        }
        , done: function (res) {
     
            //如果上传失败
            if (res.code > 0) {
     
                return layer.msg('上传失败');
            }
            //上传成功
            //打印后台传回的地址: 把地址放入一个隐藏的input中, 和表单一起提交到后台, 此处略..
             console.log(res.data.src);
             $("#companyImg").val(res.data.src);
            
            window.parent.uploadHeadImage(res.data.src);
            var demoText = $('#demoText');
            demoText.html('上传成功!!!');
        }
        , error: function () {
     
            //演示失败状态,并实现重传
            var demoText = $('#demoText');
            demoText.html('上传失败 重试');
            demoText.find('.demo-reload').on('click', function () {
     
                uploadInst.upload();
            });
        }
    });
  });

三、数据传输到后台代码为

package com.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import com.sun.javafx.collections.MappingChange.Map;
import com.tools.DateUtil;

@Controller
@RequestMapping("/upload")
public class uplond {
     

	
	/**
	 * 个人信息上传
	 * @return {Result}
	 */
	@RequestMapping(value = "/headImg", method = {
     RequestMethod.POST})
	@ResponseBody
	public Object headImg(@RequestParam(value="file",required=false) MultipartFile attach, HttpServletRequest request, HttpServletResponse response) throws Exception {
     
		String carPictuerUrl = null;
		//判断文件是否为空
		if(!attach.isEmpty()){
     
			
			  String path1 =
			  request.getSession().getServletContext().getRealPath("/");
			 
			String path = request.getSession().getServletContext().getRealPath("statics/uploadfiles");
					 
			
			System.out.println("path1:==============="+path1);
			
			System.out.println("path======"+path);
			String oldFileName = attach.getOriginalFilename();//原文件名
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
			/**
			 * RandomUtils.nextInt(1, 1000000)
	         * 返回一个在指定区间内的整数
	         * startInclusive 可以返回的最小值必须是非负的
	         * endExclusive 上限(不包括)
	         */
			//String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"."+prefix;  	
			String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1,1000000)+"."+prefix;
			File targetFile = new File(path, fileName);  //创建文件
			 if(!targetFile.exists()){
       //判断文件夹是否存在
                 targetFile.mkdirs();  
             }  
			
				try {
     
					attach.transferTo(targetFile);
				} catch (IllegalStateException e) {
     
					e.printStackTrace();
				} catch (IOException e) {
     
					e.printStackTrace();
				}
		
			 
				carPictuerUrl = "statics/uploadfiles/"+fileName;
		}
	
	    HashMap<String,Object> map2=new HashMap<String,Object>();
	    HashMap<String,Object> map=new HashMap<String,Object>();
	    map.put("code",0);
	    map.put("msg","");
	    map.put("data",map2);
	    map2.put("src",carPictuerUrl);
	    return map;
	}
	
	
	
}

四、感谢你的浏览访问

  工作几年,略有心得,然很少整理成文,平常工作中浏览了不少道友的好文章,受益良多。 
  顾也开始写一些文章, 希望能与各位道友分享进步 !!!!
  如果有用,欢迎各位点赞评论,若有不足,亦可指正!!!

你可能感兴趣的:(功能插件,upload,js,java)