Ajax实现前台上传Excel文件Java后台接收文件并保存

前台代码




    
    上传Excel
    
    







 

Java后台代码

package com.pro.warehouse.controller.Products;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class UpFileController {

    //加载页面
    @RequestMapping("/UpFile_Page")
    public String UpFilePage(ModelMap map) {
        // map.addAttribute("host", "http://www.baidu.com");
        String page = "Products/UpFile";
        return page;
    }

    @ResponseBody
    @RequestMapping("Up_File_Excel")
    public String UpFileExcel(HttpServletRequest request, @RequestParam(value = "files", required = false) MultipartFile multipartFile) throws IllegalStateException, IOException {//这里一定要写required=false 不然前端不传文件一定报错。到不了后台。
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{\"");
        jsonBuilder.append("msg\":");
        String realpath = "";
        //获取文件名
        String name = "";
        if (multipartFile != null) {
            long size = multipartFile.getSize();
            if (size > 5242880) {//文件设置大小,我这里设置5M。
                //throw new KingException(BizExceptionEnum.FILE_UPLOAD_ERROR);
                throw new NullPointerException();
            }
            name = multipartFile.getOriginalFilename();//直接返回文件的名字
            String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());//我这里取得文件后缀
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//文件保存进来,我给他重新命名,数据库保存有原本的名字,所以输出的时候再把他附上原本的名字就行了。
            //String filepath = request.getServletContext().getRealPath("/") + "files\\";//获取项目路径到webapp
            String filepath = "D:" + File.separator + "Upload_Excel" + File.separator;
            File file = new File(filepath);
            if (!file.exists()) {//目录不存在就创建
                file.mkdirs();
            }
            multipartFile.transferTo(new File(file + "\\" + name + "." + subffix));//保存文件
            realpath = file + "\\" + fileName + "." + subffix;
            jsonBuilder.append("\"" + realpath + "\"");
        }
        jsonBuilder.append("}");
        return jsonBuilder.toString();
    }
}

你可能感兴趣的:(Ajax实现前台上传Excel文件Java后台接收文件并保存)