SpringBoot文件上传下载
简单记录一下Spring Boot上传下载文件的步骤:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* @author June
*/
@Slf4j
@Controller
public class FileManagement {
@ResponseBody
@RequestMapping(path = "/fileUpload", method = RequestMethod.POST)
public String fileUpload(@RequestBody MultipartFile file) {
if (file.isEmpty()) {
log.info("File is empty !");
return "false";
}
String filename = file.getOriginalFilename();
log.info(filename);
byte[] data;
try {
data = file.getBytes();
//操作data
return "true";
} catch (IOException ioException) {
ioException.printStackTrace();
return "false";
}
}
@RequestMapping(path = "/fileDownload/{filename}", method = RequestMethod.GET)
public void fileDownload(@PathVariable String filename, HttpServletResponse response) {
if (filename.isEmpty()) {
return;
}
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
byte[] data;
try {
//数据填入data
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(data);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}