java下载文件到本地 java下载文件( 二 )


@Controller
@RequestMapping("/download")
public class DownloadController {
@RequestMapping(path = "/output1")
public void output1(HttpServletRequest request, HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
String filename = "案例案例.docx";
try {
filename = URLEncoder.encode(filename, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//中文文件名需要编码
response.setHeader("Content-Disposition", "attachment;filename=" + filename + "");
try {
String filePath = "C:\\\\Users\\\\admin\\\\Desktop\\\\案例案例.docx";
File file = new File(filePath);
response.setHeader("Content-Length", file.length() + "");
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] bytes = new byte[2048];
int r = -1;
while ((r = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, r);
}
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
【java下载文件到本地 java下载文件】}
(今完)

推荐阅读