上传
后端代码
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Date;
import java.util.UUID;
@Controller
public class TestUploadController {
@RequestMapping("/toUpLoadPage")
public String toPage(){
return "/testUpload.html";
}
@RequestMapping(value = "upload",method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
if (!file.isEmpty()) {
try {
String filePath = "d:/files/";
String fileName = file.getOriginalFilename();
String path = filePath + fileName ;
File upLoadFile = new File(path);
FileOutputStream out = new FileOutputStream(upLoadFile);
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
}
return "上传成功";
} else {
return "上传失败,因为文件是空的.";
}
}
}
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 模板</title>
<meta charset="UTF-8">
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<div class="form-group">
<label for="file">文件输入1</label>
<input type="file" id="file" name="file">
</div>
<button type="submit">提交</button>
</form>
</body>
</html>
下载
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@Controller
public class TestDownLoadController {
@RequestMapping("/downLoad")
@ResponseBody
public String downLoad(HttpServletResponse response) throws IOException {
File file = new File("D:\\files\\123.xlsx");
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + "123.xlsx");
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] bt = new byte[1024];
int i = bufferedInputStream.read(bt);
while (i != -1){
outputStream.write(bt,0,i);
i=bufferedInputStream.read(bt);
}
fileInputStream.close();
bufferedInputStream.close();
outputStream.close();
return "下载成功";
}
}