参考:https://stackoverflow.com/questions/1442893/implementing-a-simple-file-download-servlet,并做了好几处改进
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
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 com.bupt.nctc.service.impl.FileService;
/**
* 文件的Controller类
* @create 2018年1月18日
*/
@Controller
@RequestMapping("/file")
public class FileControllerUtils {
//如:http://localhost:8080/file/download?name=E:/a.xls
@ResponseBody
@RequestMapping(value = "/download", method = RequestMethod.GET)
public Object download(@RequestParam(name="name", required=true) String name,
HttpServletRequest request, HttpServletResponse response) {
try {
String filePath = name;// 如 E:/test.docx
// You must tell the browser the file type you are going to send
// for example application/pdf, text/plain, text/html, image/jpg
String fileType = "text/plain";//纯文本
response.setContentType(fileType);
String fileName = "";
int pos = 0;
if( (pos = filePath.lastIndexOf("/")) > 0 ) {
fileName = filePath.substring(pos + 1, filePath.length());//截取文件名字
} else { fileName = filePath;} //没有父文件夹,如"1.txt"
//设置响应头
//适应中文文件名
response.setHeader("Content-disposition","attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
// Assume file name is retrieved from database
// For example D:\\file\\test.pdf
File my_file = new File(filePath);
System.out.println("要下载文件:" + my_file);
if( !my_file.exists()){
throw new Exception("文件不存在");
}
// This should send the file to browser
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
System.out.println("下载成功: " + name );
return null;
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
Map<String, String> map=new HashMap<String, String>();//返回成功、失败信息
map.put("status", "false");
map.put("reason", e.getMessage());
return map;
}
}
}