
⒈文件实体类
package cn.coreqi.security.entities; public class FileInfo { private String path; public FileInfo(String path) {
this.path = path;
} public String getPath() {
return path;
} public void setPath(String path) {
this.path = path;
}
}
⒉控制器代码
package cn.coreqi.security.controller; import cn.coreqi.security.entities.FileInfo;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date; @RestController
public class FileController { @PostMapping("/file")
public FileInfo upload(MultipartFile file) throws IOException {
System.out.println(file.getName()); //文件名
System.out.println(file.getOriginalFilename()); //原始文件名
String folder = "d:/test";
File localFile = new File(folder,new Date().getTime() + ".txt");
file.transferTo(localFile); //将上传的文件写入到本地的文件中
return new FileInfo(localFile.getAbsolutePath()); //绝对路径
} @GetMapping("/file/{id}")
public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response){
try(
InputStream inputStream = new FileInputStream(new File("d:/test/1553692860875.txt"));
OutputStream outputStream = response.getOutputStream();
) {
response.setContentType("application/x-download");
response.addHeader("Content-Disposition","attachment;filename=test.txt");
IOUtils.copy(inputStream,outputStream);
outputStream.flush(); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
⒊测试
/**
* 上传文件测试
*/
@Test
public void whenUploadSuccess() throws Exception {
//mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file")
String result = mockMvc.perform(MockMvcRequestBuilders.multipart("/file")
.file(new MockMultipartFile("file","test.txt","multipart/form-data","hello upload".getBytes("UTF-8"))))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}