上篇文章說的是檔案的預覽,這裡來說一下檔案的下載下傳,出入職場,種種不足歡迎指出,由于xml檔案的格式比較特殊,因為和html存在沖突,是以在這裡說明一下我用的是這個标簽,因為 标簽之間的内容不會被當作文檔内容解析,而會被用等寬字型直接呈現。
@RequestMapping(value = "/previewFile", method = RequestMethod.GET)
public String previewFile(String key, String fileFormat) {
String url = getPath(key);
String aimPath = url.replace(fileFormat, ".html");
String encode = "";
String fileContent = "";
try {
encode = EncodingDetect.getJavaEncode(url);
fileContent = FileUtils.readFileToString(new File(url), encode);
} catch (Exception e) {
logger.warn("檔案轉換異常");
}
File newfile = new File(aimPath);
String str = "<html><head></head><title>" + newfile.getName() + "</title><xmp style='margin-left: 5px;'>" + fileContent + "</xmp></html>";
return str;
}
本身是下載下傳+預覽的功能,這裡主要介紹下載下傳
<body>
<button onclick="downLoad()" id="btn">下載下傳</button>
<iframe id="mainframe" style="float: left;width:100%;height:96%;" frameborder="0" scrolling="auto"></iframe>
</body>
function downLoad() {
window.location.href = baseURL + "cms/systemModuleFileCollectNonCommon/downLoadFile?path=" + encodeURIComponent(filePath)+"&&ip="+ip;
}
後端下載下傳的java接口
//儲存檔案
@RequestMapping("downLoadFile")
public void downLoadFile(String ip, String path, HttpServletRequest request, HttpServletResponse response) {
try {
path = getPath(path);
File file = new File(path);
String name = file.getName();
String ori = name.substring(0, name.lastIndexOf("."));
String rev = name.substring(name.lastIndexOf("."), name.length());
FileInputStream inputStream = null;
inputStream = new FileInputStream(file);
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(ori + "(" + ip + ")" + rev, "UTF-8"));
OutputStream out = response.getOutputStream();
///向out中寫入流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
response.flushBuffer();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
}
到這裡下載下傳的功能就完成了,歡迎指正不足