Springboot MultipartFile ajax提交java文件上传

ecplise

jdk 1.8

一。配置信息

pom.xml 文件引入以来依赖

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-thymeleaf

2、springboot 启动类Application

增加@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})

3、application.yml文件

增加文件大小限制,上传的根目录

multipart:

  enabled: true

  max-file-size: 50mb

  max-request-size: 50mb

上传的根目录

#公用变量,方便更改

publicvariable:

    #项目图片保存路径

    imglocation: /Users/wangdeqiu/Documents/fileUpload

 

二、index.html页面提交上传文件

Title

    文件:   

 

 

三、Java controller 接受参数,调用service

@Controller

@RequestMapping("test")

public class TestBootController {

    //日志打印

    private final Logger log = LoggerFactory.getLogger(TestBootController.class);

    @Autowired

    private FileUploadService fileUploadService;

   Logger logger = LoggerFactory.getLogger(TestBootController.class);

 

            @RequestMapping("/")

            public String home() {

                 return "app/index";

           }

 

       @RequestMapping(value = "/upload", method = RequestMethod.POST)

       @ResponseBody

        public Map  saveUploadFile( @RequestParam("file") MultipartFile file,HttpServletRequest request) {

               Map  output = new HashMap();

             String fileName = file.getOriginalFilename();

             System.out.println("获取....fileName.."+fileName);

          try {

                  String fileType = "合同";

                 UploadFile fileEntity = fileUploadService.uploadFile(file,fileType);

                System.out.println("setfileName显示的文件名"+fileEntity.getFileName());

                System.out.println("setFilePath文件路径"+fileEntity.getFilePath());

                System.out.println("setRealName真正的文件名"+fileEntity.getRealName());

                System.out.println("setSuffix文件后缀"+fileEntity.getSuffix());

          } catch (IllegalStateException e) {

                logger.error("文件上传错误", e.getMessage());

                e.printStackTrace();

                throw e;

         } catch (IOException e) {

             logger.error("文件上传错误", e.getMessage());

             e.printStackTrace();

        } catch (Exception e) {

             output.put("msg", "上传失败");

             e.printStackTrace();

       }

           return output;

    }

}

2、Servie 文件上传

package com.haidaipuhui.service.common;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.haidaipuhui.domain.common.UploadFile;
import com.haidaipuhui.util.FileUploadUtil;

/**
 * @date 2018年7月30日 下午2:06:39
 * 类说明:文件的上传与下载
 */
@Service
public class FileUploadService {

   
    @Value("${publicvariable.imglocation}")
    private String rootPath;//文件根路径
    
    /**
     * 
     * Desc:文件上传
     * @author wangdeqiu
     * @date 2018年7月30日 下午2:08:33
     * @return
     * @param file  上传的文件
     * @param fileType 根据累心创建文件夹 例如:合同,企业资料。
     * @throws Exception 
     */
    public UploadFile uploadFile(MultipartFile file,String fileType) throws Exception {
        UploadFile fileEntity = new UploadFile();
         if (file.isEmpty() || StringUtils.isBlank(file.getOriginalFilename())) {
               throw new Exception();
         }
        String[] fileItem = file.getOriginalFilename().split("\\.");
        String uuid_name = UUID.randomUUID().toString();
        String relativePath = FileUploadUtil.getUploadPath()+FileUploadUtil.flag;
        String filePath = rootPath+"/"+fileType+"/"+relativePath+uuid_name+"."+fileItem[1];
        String path = rootPath+"/"+fileType+"/"+relativePath;//根目录+类型+时间
//        File targetFile = new File(path);
//        if(!targetFile.exists()){
//            targetFile.mkdirs();
//        }
//        file.transferTo(targetFile);
         File tarFile = new File(path);
            if (!tarFile.exists()) {
                    tarFile.mkdirs();
            }
        String fileName = uuid_name+"."+fileItem[1];
        FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        
        fileEntity.setFileName(fileItem[0]);
        fileEntity.setRealName(uuid_name);
        fileEntity.setFilePath(relativePath);
        fileEntity.setSuffix(fileItem[1]);
        return fileEntity;
    }

}

3、FileUploadUtil 

package com.haidaipuhui.util;

import java.util.Calendar;

import java.util.Date;

 public class FileUploadUtil {

           public static final String flag = "/";

 

          /**

         * @title getUploadPath 

         * @Description: 获取日月年文件夹路径 

          */

         public static String getUploadPath(){

                  Calendar calendar = Calendar.getInstance();

                   calendar.setTime(new Date());

                  String yearPath = Integer.toString(calendar.get(Calendar.YEAR));

                  String monthPath = Integer.toString(calendar.get(Calendar.MONTH)+1);

                  String datePath = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));

                   return flag+yearPath+flag+monthPath+flag+datePath+flag;

          }

}

   

  

 

 

你可能感兴趣的:(Java学习记录,Jquery,+JS,springboot)