原生文件上传代码

前端lauyi

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="<%=request.getContextPath()%>/layui/css/layui.css">

    <script src="<%=request.getContextPath()%>/js/common.js">script>
    <script src="<%=request.getContextPath()%>/js/UrlRouter.js">script>
    <script src="<%=request.getContextPath()%>/js/jquery.js">script>

    <style>
        #preview img {
            max-height: 150px;
        }
    style>
head>
<body style="padding: 15px">
<div>新增广告div>

<form class="layui-form" action="">

    <div class="layui-form-item">
        <div class="layui-upload-drag" id="chooseImage">
            <i class="layui-icon">i>
            <p>点击上传图片,或将图片文件拖拽到此处p>
        div>

        <div>
            <div id="preview" >div>
            <input type="hidden" name="imageUrl">
        div>
    div>


    <div class="layui-form-item">
        <div class="layui-input-inline" style="width: 120px;">
            <input type="text" name="bgColor" value="" placeholder="请选择颜色" class="layui-input"
                   id="bgColor-form-input">
        div>
        <div class="layui-inline" style="left: -11px;">
            <div id="chooseColor">div>
        div>
    div>

    <div class="layui-form-item">
        <div class="layui-input-inline">
            <button class="layui-btn" lay-submit="" lay-filter="adSubmit">立即提交button>
        div>
    div>

form>

<script src="<%=request.getContextPath()%>/layui/layui.all.js" charset="UTF-8">script>
<script>
    var colorpicker, upload, form,layer ;
    layui.use(['form', 'colorpicker', 'upload'], function () {
        form = layui.form;
        layer = layui.layer;
        colorpicker = layui.colorpicker;
        upload = layui.upload;

        //表单赋值
        colorpicker.render({
            elem: '#chooseColor'
            , color: '#e63c22'
            , done: function (color) {
                $('#bgColor-form-input').val(color);
            }
        });

        //拖拽上传
        upload.render({
            elem: '#chooseImage'
            , url: baseUrl + '/api/upLoadImages'
            , accept: 'file' //普通文件
            , done: function (res) {
                console.log(res)
                $("#preview").html('+ res.data.src + '" alt="" class="layui-upload-img">');
                $("input[name='imageUrl']").val(res.data.src)
                layer.msg('上传成功');
            }, error: function (res) {
                console.log(res)
                layer.msg('上传失败', {
                    icon: 1,
                    time: 3000 //2秒关闭(如果不配置,默认是3秒)
                }, function(){
                    //do something
                });
            }
        });

        //监听提交
        form.on('submit(adSubmit)', function(data){
            console.log(data);
            var imageUrl = data.field.imageUrl ;
            var bgColor = data.field.bgColor ;
            if(!imageUrl){
                layer.msg("请选择图片");
                return false;
            }
            if(!bgColor){
                layer.msg("请选择背景颜色");
                return false;
            }


            // layer.alert(JSON.stringify(data.field), {
            //     title: '最终的提交信息'
            // });

            var uploadData = data.field ;
            uploadData.method = "create" ;

            $.ajax({
                url: baseUrl + "/api/ad",
                data:uploadData,
                type: "post",
                dataType: "json",
                success: function (jsonData) {
                    layer.msg(jsonData.msg);
                },
                error:function () {

                }
            })


            return false;
        });
    })


script>
body>
html>

servlet接受图片

public class upLoadImageServlet extends BaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out =response.getWriter();
        String path="/upLoadImages";
//        获取绝对路径(工程在服务器上的绝对路径)
        String savePath=request.getServletContext().getRealPath(path);
//        out.println(savePath);
        File savePathFile = new File(savePath);
        if(!savePathFile.exists()){
            savePathFile.mkdirs();
        }
        Part part=request.getPart("file");
        String header = part.getHeader("Content-Disposition");
        String fileName = System.currentTimeMillis() + "_" + getFileName(header);
        String allPath=savePath+File.separator+fileName;
        part.write(allPath);
//        BaseResp baseResp=new BaseResp<>(1,"成功",allPath);
        BaseResp<ImagePath> baseResp=new BaseResp<>();
        ImagePath imagePath=new ImagePath();
        imagePath.setSrc(request.getContextPath()+path+"/"+fileName);
        baseResp.setCode(0);
        baseResp.setMsg("上传成功");
        baseResp.setData(imagePath);
        out.println(gson.toJson(baseResp));
    }
    public  String getFileName(String header){
        String[] tempArr1=header.split(";");
        String[] tempArr2=tempArr1[2].split("=");
        return tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"","");
    }

bean回参数

package com.sy.store.bean.base;

public class BaseResp<T> {
    public  static final int code_sucess=1;
    public static  final  int code_falled=0;
    private  int code;
    private  String msg;
    private  T data;

    public BaseResp() {
    }

    public BaseResp(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static int getCode_sucess() {
        return code_sucess;
    }

    public static int getCode_falled() {
        return code_falled;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

上传成功后前端,提交返回图片路径给后端

 public void createAd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        AdService adService=new AdServiceImpl();
        String imageUrl = request.getParameter("imageUrl");
        String bgColor = request.getParameter("bgColor");
        Ad ad =new Ad(imageUrl,bgColor,1,1);
        BaseResp baseResp=new BaseResp();
        boolean count= false;
        try {
            count = adService.insertAd(ad);
            if (count){
                baseResp.setCode(BaseResp.code_sucess);
                baseResp.setMsg("插入成功");
            }else {
                baseResp.setCode(BaseResp.code_falled);
                baseResp.setMsg("插入失败");
            }
        } catch (StoreException e) {
            e.printStackTrace();
            baseResp.setCode(BaseResp.code_falled);
            baseResp.setMsg(e.getMessage());
        }
        System.out.println(count?"插入成功":"插入失败");
//插入数据返回参数
        response.getWriter().println(gson.toJson(baseResp));
    }

你可能感兴趣的:(原生文件上传代码)