layui多文件上传

layui官方文档代码

文件名 大小 状态 操作

js代码

后台controller代码

package com.example.demo1.controller;

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 java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xx
 * @version 1.0
 * @date 2020/6/21 15:47
 */

@Controller
@RequestMapping(value = "/data")
public class DataController {

    @RequestMapping(value="/uploadSource" , method = RequestMethod.POST)
    @ResponseBody
    public String uploadSource(@RequestParam("file") MultipartFile file) {
        System.out.println(file);
        String pathString = null;
        if(file!=null) {
        //获取上传的文件名称
        String filename = file.getOriginalFilename();
        //文件上传时,chrome与IE/Edge对于originalFilename处理方式不同
        //chrome会获取到该文件的直接文件名称,IE/Edge会获取到文件上传时完整路径/文件名
        //Check for Unix-style path
        int unixSep = filename.lastIndexOf('/');
        //Check for Windows-style path
        int winSep = filename.lastIndexOf('\\');
        //cut off at latest possible point
        int pos = (winSep > unixSep ? winSep:unixSep);
        if (pos != -1)
            filename = filename.substring(pos + 1);
            pathString = "E:/upload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" +filename;//上传到本地
        }
        try {
            File files=new File(pathString);//在内存中创建File文件映射对象
            //打印查看上传路径
            System.out.println(pathString);
            if(!files.getParentFile().exists()){//判断映射文件的父文件是否真实存在
                files.getParentFile().mkdirs();//创建所有父文件夹
            }
            file.transferTo(files);//采用file.transferTo 来保存上传的文件
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "{\"code\":0, \"msg\":\"success\", \"fileUrl\":\"" + pathString + "\"}";
    }
}

上传成功显示页面

layui多文件上传_第1张图片

 

  • 返回值问题
    layui官方代码要求返回的json格式
  •  
{
  "code": 0
  ,"msg": ""
  ,"data": {
    "src": "http://cdn.layui.com/123.jpg"
  }
}

获取上传文件到项目里面

@ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public void uploadFile(HttpServletRequest request, HttpServletResponse response , HttpSession session, MultipartFile file) throws Exception{
        PageData pd = new PageData(request);
        String filename = file.getOriginalFilename();// 文件原名称
        String fileSuffix = filename.substring(filename.lastIndexOf("."));//文件类型
        String fileType = filename.substring(filename.lastIndexOf(".")+1);//文件后缀

        //保存文件
        File directory = new File("");// 参数为空
        String savePath = directory.getCanonicalPath();
        String path = "/upload/commomFile/"+DateTimeUtil.getDate()+"/"+ GuidUtil.getGuid()+fileSuffix;
        File files = new File(savePath+path);
        if (!files.getParentFile().exists()){
            files.getParentFile().mkdirs();
        }
        file.transferTo(files);
        pd.put("name",filename);
        pd.put("desnames",filename);
        pd.put("file_path",path);
        pd.put("file_type",fileType);
        pd.put("file_size",files.length());
        pd.put("obj_id","");
        pd.put("file_suffix",fileSuffix);
        pd.put("source",pd.get("type"));
        pd.put("order_by","1");

        PageData user = (PageData) session.getAttribute("loginUser");
        pd.put("create_user",user.get("id"));
        pd.put("create_organize",user.get("organize_id"));
        pd.put("create_org_cascade",user.get("org_cascade"));
        pd.put("create_time", DateTimeUtil.getDateTimeStr());
        pd.put("update_time",DateTimeUtil.getDateTimeStr());
        uploadService.saveFile(pd);

        Json json = new Json();
        json.setSuccess(true);
        json.setData(pd);
        json.setMsg(pd.get("id")+"#"+path+"#"+filename);
        this.writeJson(response,json);
    }

 上传到本地文件

/**
     * @Description: uploadFile
     * @Param: [request, response, session, file]
     * @return: void
     * @Author: x
     * @Date: 2019-3-11 11:04
     */
    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadSource(@RequestParam("file") MultipartFile file) {
        System.out.println(file);
        String pathString = null;
        if(file!=null) {
            //获取上传的文件名称
            String filename = file.getOriginalFilename();
            //文件上传时,chrome与IE/Edge对于originalFilename处理方式不同
            //chrome会获取到该文件的直接文件名称,IE/Edge会获取到文件上传时完整路径/文件名
            //Check for Unix-style path
            int unixSep = filename.lastIndexOf('/');
            //Check for Windows-style path
            int winSep = filename.lastIndexOf('\\');
            //cut off at latest possible point
            int pos = (winSep > unixSep ? winSep:unixSep);
            if (pos != -1)
                filename = filename.substring(pos + 1);
            pathString = "E:/upload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" +filename;//上传到本地
        }
        try {
            File files=new File(pathString);//在内存中创建File文件映射对象
            //打印查看上传路径
            System.out.println(pathString);
            if(!files.getParentFile().exists()){//判断映射文件的父文件是否真实存在
                files.getParentFile().mkdirs();//创建所有父文件夹
            }
            file.transferTo(files);//采用file.transferTo 来保存上传的文件
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "{\"code\":0, \"msg\":\"success\", \"fileUrl\":\"" + pathString + "\"}";
    }

综合修改了一下

/**
     * @Description: LocalFile
     * @Param: [request, response, session, file]
     * @return: void
     * @Author: x
     * @Date: 2019-6-20 15:34
     */
    //上传app
    @RequestMapping(value = "/LocalFile", method = RequestMethod.POST)
    @ResponseBody
    public HashMap uploadLocalFile(HttpServletRequest request, HttpServletResponse response , HttpSession session, @RequestParam("file") MultipartFile file) throws Exception{
        PageData pd = new PageData(request);
        String filename = file.getOriginalFilename();// 文件原名称
        String fileSuffix = filename.substring(filename.lastIndexOf("."));//文件类型
        String fileType = filename.substring(filename.lastIndexOf(".")+1);//文件后缀

        //保存文件
//        String savePath= request.getSession().getServletContext().getRealPath("/");//地址在本项目
        String savePath= "E:/AppFile/";//现在在本地E盘AppFile
//        String savePath = ParaUtil.localName;
        String path = ParaUtil.common+ DateTimeUtil.getDate()+"/";
        String appfile = GuidUtil.getGuid()+fileSuffix;
//        System.out.println(appfile);

        File files = new File(savePath+path+appfile);
        if (!files.getParentFile().exists()){
            files.getParentFile().mkdirs();
        }
        file.transferTo(files);
//        return "{\"code\":0, \"msg\":\"success\", \"fileUrl\":\"" + path + "\"}";

        //放入集合
        List filelist =new ArrayList();
        filelist.add(savePath);
        filelist.add(path);
        filelist.add(appfile);

        //转换格式返回文件名和存放文件夹
        HashMap map = new HashMap();
        map.put("code", 0);
        map.put("msg", "操作成功");
        map.put("data", filelist);
        return map;

    }

 

页面显示

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="../../system/admin/top.jsp"%>

<%--
版本更新
版本:* 下载地址:*
--%> <%-- --%> <%-- --%> <%--
文件名 大小 状态 操作
--%>
<%@include file="../../system/admin/bottom.jsp"%>

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(后端,前端)