项目中源代码如下:
@RequestMapping("downloadattr")
@ResponseBody
public void downloadattr(HttpServletRequest request, HttpServletResponse response) {
//服务器中文件的路径
String url = request.getParameter("url");
String[] fullName = url.split("/");
//本次代码的url用"/"分割后最后一段是文件名
String attaName = fullName[fullName.length - 1];
attaName.substring(14, attaName.length());
try {
//设置编码为utf-8
String filePath = java.net.URLDecoder.decode(url, "UTF-8");
// 读取临时文件并写出
File file = new File(filePath);
if (file.exists()) {
InputStream in = new FileInputStream(file);
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-disposition", "attachment; filename=" + attaName);
response.setContentType("application/msword");
OutputStream outWrite = response.getOutputStream();
// 一次读多个字节
byte[] tempBytes = new byte[100];
int byteRead = 0;
// 读入多个字节到字节数组中,byteRead为一次读入的字节数
while ((byteRead = in.read(tempBytes)) != -1) {
outWrite.write(tempBytes, 0, byteRead);
}
in.close();
outWrite.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
主要内容为try-catch里面的,可以复制粘贴,改改地址和文件名字就可以了