導入commos-fileupload
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
SpringMVC爲文件上傳提供了直接的服務,這種支持是用即插即用的MultipartResolver實現的
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--請求的編碼格式,必須和jsp的pageEncoding屬性一直,默認ISO-8859-1-->
<property name="defaultEncoding" value="utf-8"/>
<!--最大上傳大小10m-->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
要求:前端的method設置爲post,並且enctype設置爲multipart/from-data
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/4/14
Time: 20:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="upload"/>
</form>
</body>
</html>
package com.zjx.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
/**
* 文件上傳
* 圖片下載
* @author zjx
* @date 2020/4/14 20:36
*/
@RestController
public class UploadController {
/**
* 文件上傳方式一
* @param file 前端上傳的文件
* @param request
* @return
* @throws Exception
*/
//@RequestParam("file")CommonsMultipartFile file
//將name=file控件得到的文件封裝成 CommonsMultipartFile
//如果是批量刪除CommonsMultipartFile爲數組即可
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws Exception {
//處理請求 獲取上傳的文件名
String uploadFileName = file.getOriginalFilename();
//判斷文件名是否爲空
if ("".equals(uploadFileName)) {
return "redirect:/index.jsp";//重定向到首頁
}
System.out.println("上傳的文件名爲:" + uploadFileName);
//上傳路徑保存設置
String path = request.getServletContext().getRealPath("/upload");
//如果路徑不存在就創建
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();//創建這個路徑
}
System.out.println("文件上傳保存地址爲:" + realPath);
//獲取文件輸入流
InputStream is = file.getInputStream();
//獲取文件輸出流
//拼接文件路徑和文件名
FileOutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
//邊讀邊寫
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
os.flush();//刷新緩衝區
}
os.close();
is.close();
return "redirect:/index.jsp";//保存完畢重定向
}
/**
* 文件上傳方式二
* @param file 前端上傳的文件
* @param request
* @return
* @throws Exception
*/
@GetMapping("/upload2")
public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws Exception {
//上傳路徑保存設置
String path = request.getServletContext().getRealPath("/upload");
//如果路徑不存在就創建
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();//創建這個路徑
}
//通過CommonsMultipartFile的方法直接寫文件
file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
return "redirect:/index.jsp";//保存完畢重定向
}
/**
* 圖片下載
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/download")
public String downloads(HttpServletRequest request, HttpServletResponse response) throws Exception{
//要下載的圖片地址
String path = request.getServletContext().getRealPath("/upload");
String fileName = "star.jpg";
//設置響應頭
response.reset();//設置頁面不緩存 清空buffer
response.setContentType("UTF-8");
response.setContentType("multipart/form-data");//二進制傳輸數據
response.setHeader("Content-Disposition",
"attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
//根據路徑創建File對象
File file = new File(path,fileName);
//讀取文件
FileInputStream input = new FileInputStream(file);
//寫出文件
OutputStream out = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = input.read(buffer)) != -1) {
out.write(buffer, 0, len);
out.flush();//刷新緩衝區
}
out.close();
input.close();
return "ok";
}
}
或者
/**
* HttpMessageConveter
* 下載
* 支持 RequestBody ResponseBody HttpEntity ResponseEntity
* 下載的原理:將服務器端的文件以流的形式到客戶端
*/
@RequestMapping("/download")
public ResponseEntity<byte[]> testDown(HttpSession session) throws IOException {
//將要下載的文件讀取成一個字節數組
byte[] imgs;
ServletContext sc = session.getServletContext();
InputStream in = sc.getResourceAsStream("image/test.jpg");
imgs = new byte[in.available()];
in.read(imgs); //讀取到字節數組中
//將響應數據以及響應頭封裝到Entity中
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Disposition","attachment;filename=mimi.jpg");
ResponseEntity<byte[]> re
= new ResponseEntity<byte[]>(imgs,httpHeaders, HttpStatus.OK);
return re;
}