springboot 簡單的上傳文檔或者圖片,並且進行操作,操作完後進行保存指定路徑。兩個方法就解決
1、上傳配置
package com.example.demo.config;
/**
* \* Created with IntelliJ IDEA.
* \* @author wcy
* \* @date: 2019/12/24
* \* @time: 15:03
* \* Description:
* \
*/
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.servlet.MultipartConfigElement;
@Configuration
public class UploadFileProperties extends WebMvcConfigurerAdapter {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 設置文件大小限制 ,超出設置頁面會拋出異常信息,
// 這樣在文件上傳的地方就需要進行異常信息的處理了;
factory.setMaxFileSize("128MB"); // KB,MB
/// 設置總上傳數據總大小
factory.setMaxRequestSize("256MB");
//設置文件路徑
//factory.setLocation("");
return factory.createMultipartConfig();
}
}
2、實現controller 方法
import com.alibaba.fastjson.JSON;
import com.example.demo.service.FunctionAriService;
import com.example.demo.service.SumMoneyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileOutputStream;
import java.io.IOException;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String uploadExcel(@RequestParam("file") MultipartFile file) {
if (file == null) {
return "讀取失敗";
}
// 可以對文件進行讀寫操作,這裏就不寫了
// String result =functionAriService.resolveExcel(file);
try {
// 建上傳的文件保存到指定路徑
// 保存的路徑的文件,可以根據自己編寫路徑
String path = "d:\\file\\Desktop\\1\\";
// 獲取文件名或者自己根據規則進行文件名編寫,可以進行簡單的判斷是否獲取到文件
String fileName = file.getOriginalFilename();
try {
// 將文件保存到指定路徑的功能
FileOutputStream out = new FileOutputStream(path+fileName);
out.write(file.getBytes());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
loggge.error(JSON.toJSONString(e));
}
return "運行結束";
}
3、使用postman 進行Http請求