文件上傳
1. springmvc中使用commons-fileupload 與 commons-io完成文件上傳
/**
* 文件上傳需要使用到兩個jar包:
* 1. commons-fileupload.jar
* 2. commons-io.jar
* 配置springmvc的配置文件-配置文件上傳的解析器 CommensMultipartResolver
* @throws IOException
*/
@RequestMapping("/upload")
public String fileupload (@RequestParam("file") CommonsMultipartFile file, HttpServletRequest req, HttpServletResponse res) throws IOException {
// 獲取文件名
String fileName = file.getOriginalFilename()
//獲取文件上傳路徑
String path = req.getRealPath("/fileupload");
// 獲取文件輸入流
InputStream is = file.getInputStream();
// 獲取輸入出流
OutputStream os = new FileOutputStream(new File(path, file.getOriginalFilename()));
// 開始讀寫文件
int len = 0;
byte[] buf = new byte[400];
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.close();
is.close();
return "上傳成功";
}
2. springboot中使用commons-fileupload 與 commons-io完成文件上傳
2.1 pom.xml引入依賴
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2.2 處理邏輯
//獲取文件存儲路徑
@Value("${filePath}")
private String filePath;
@RequestMapping(value ="/fileUp", method = RequestMethod.POST)
@ResponseBody
public void fileUploadOne(@RequestParam("file") MultipartFile file,@RequestParam("fileType") String fileType) {
// 獲得原始文件名+格式
String fileName = file.getOriginalFilename();
//截取文件名
String fname = fileName.substring(0, fileName.lastIndexOf("."));
//截取文件格式
String format = fileName.substring(fileName.lastIndexOf(".") + 1);
//獲取當前時間(精確到毫秒)
long MS = System.currentTimeMillis();
String timeMS = String.valueOf(MS);
//原文件名+當前時間戳作爲新文件名
String videoName = fname + "_" + timeMS + "." + format;
String filelocalPath = "";
char pathChar = upfilePath.charAt(upfilePath.length() - 1);
Date date = new Date();
String dateOne = new SimpleDateFormat("yyyy/MM/dd/").format(date);
if (pathChar == '/') {
filelocalPath = upfilePath + dateOne;
} else {
filelocalPath = upfilePath + "/" + dateOne;
}
File f = new File(filelocalPath);
if (!f.exists())
f.mkdirs();
if (!file.isEmpty()) {
try {
FileOutputStream fos = new FileOutputStream(filelocalPath + videoName);
InputStream in = file.getInputStream();
//InputStream in = request.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = in.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.3 上傳限制
在Application啓動類中添加註解@configuration 並設置上傳文件的大小
//獲取配置的上傳文件的系統臨時文件夾路徑
@Value("${tempfilePath}")
private String tempfilePath;
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//允許上傳的文件最大值
factory.setMaxFileSize("100MB");
/// 設置總上傳數據總大小
factory.setMaxRequestSize("1024MB");
//設置臨時文件路徑,以防長時間不操作後刪除臨時文件導致報錯
File f = new File(tempfilePath);
if (!f.exists())
f.mkdirs();
factory.setLocation(tempfilePath);
return factory.createMultipartConfig();
}
3. 使用springboot默認上傳
3.1 處理邏輯
@RequestMapping(value="/upload")
public String upload (@RequestParam("hjkFile") MultipartFile file, Model model) throws IllegalStateException, IOException {
System.out.println("fileName:" + file.getOriginalFilename());
// 獲取文件名
String fileName = file.getOriginalFilename();
// 獲取文件後綴名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 文件上傳存儲路徑
String filePath = "e:/upload/";
// 唯一處理文件名
fileName = filePath + UUID.randomUUID() + fileName;
// 聲明文件實例
File desFile = new File(fileName);
// 判斷文件是否存在
if (!desFile.getParentFile().exists()) {
// 不存在則新建
desFile.getParentFile().mkdirs();
}
// 文件內容轉移至服務器磁盤存儲
file.transferTo(desFile);
model.addAttribute("msg", "上傳成功!");
return "upload";
}
3.2 上傳限制
配置文件 application.properties 增加配置
#配置文件傳輸
spring.servlet.multipart.enabled =true
spring.servlet.multipart.file-size-threshold =0
#單個數據的大小
spring.servlet.multipart.max-file-size = 100Mb
#總數據的大小
spring.servlet.multipart.max-request-size=100Mb
在Application啓動類中添加註解@configuration 並設置上傳文件的大小
/**
* 配置上傳文件大小的配置
*
* @return
*/
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 單個數據大小
factory.setMaxFileSize("102400KB");
/// 總上傳數據大小
factory.setMaxRequestSize("102400KB");
return factory.createMultipartConfig();
}