引言
每次做图片上传的时候都要去网上去找,我干脆自己写一个小demo出来以后自己用,这篇就当作是给自己做的一个笔记吧。
一、例子
/**
* @ClassName:
* @User: ljh
* @Date: 2022/12/19 15:01
*/
@RestController
public class IoController {
@GetMapping("/download")
public void download(@RequestParam("file") MultipartFile file,
HttpServletResponse response) throws Exception {
String path = "E://";
String filename = URLEncoder.encode("test.png", "UTF-8");
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + filename);//浏览器上提示下载时默认的文件名
ServletOutputStream out = response.getOutputStream();
InputStream stream = file.getInputStream();
try {//读取服务器上的文件
byte buff[] = new byte[file.getBytes().length];
int length = 0;
while ((length = stream.read(buff)) > 0) {
out.write(buff, 0, length);
}
File newFile =new File(path + filename);
file.transferTo(newFile);
stream.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上就是图片上传的小demo啦,如果哪里有写错的,欢迎大佬指出!