1. 程式人生 > >Springboot MultipartFile ajax提交java檔案上傳

Springboot MultipartFile ajax提交java檔案上傳

ecplise

jdk 1.8

一。配置資訊

pom.xml 檔案引入以來依賴

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!-- 檢視解析Thymeleaf -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

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頁面提交上傳檔案

<!DOCTYPE HTML>

<html xmlns:th="http://www.thymeleaf.org">

<head>

<title>Title</title>

<!-- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> -->

<meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />

<meta http-equiv="X-UA-Compatible" content="IE=8, IE=9, IE=10, chrome=1" />

<script src="/js/jquery.js"></script>

</head>

<body>

<form id="uploadForm" enctype="multipart/form-data">

    檔案:<input id="file" type="file" name="file" text="點選我上傳圖片"  />   

</form> 

<button id="upload">上傳檔案</button>

<script type="text/javascript">

 $(function () {

        $("#upload").click(function () {

               var fileObj = document.getElementById("file").files[0]; // js 獲取檔案物件

               var tokenv="ssssssss";

               //var data = {"token":token,"file":fileObj};

                var formData = new FormData();

                formData.append("file",fileObj);

               formData.append("token",tokenv);

            $.ajax({

                 url: 'http://localhost:8080/test/upload',

               type: 'POST',

              cache: false,

              data: new FormData($('#uploadForm')[0]),

             processData: false,

            contentType: false

       }).done(function(res) {

           //列印返回值資訊

           alert(res);

     }).fail(function(res) {

          alert("上傳失敗");

    });

  });  

}); 

</script>

</body>

</html>

三、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<String,Object>  saveUploadFile( @RequestParam("file") MultipartFile file,HttpServletRequest request) {

               Map<String,Object>  output = new HashMap<String,Object>();

             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;

          }

}