我试图用spring和ajax保存一个pdf文件。请求被发送和接收,但它卡在网络中。如何获取该url或保存文件(红色圆圈)。我使用的是SpringBoot,javascript,jquery和ajax。如果你有更好的保存方法,请告诉我。
@RequestMapping(value = "/secure/configPDF/export.jspa",method = RequestMethod.GET)
public void exportPDF(HttpServletRequest req, HttpServletResponse resp, Model model) throws ServletException, IOException {
String html = req.getParameter("html");
String json = req.getParameter("json");
InputStream inputStream = null;
OutputStream outputStream = null;
Object[] res= new Object[2];
File file =null;
File dir = null;
String idString = String.valueOf(req.getParameter("id"));
String errors="";
long id = 0;
if (idString.isEmpty() != true || idString.equalsIgnoreCase("") != true) {
id = Long.parseLong(idString);
}
try{
JSONObject jsonObject = new JSONObject(json);
}catch (JSONException sd){
//errors+=sd.toString();
}
String type = req.getParameter("type");
ApplicationUser user = authenticationContext.getUser();
try {
if (StringUtils.isBlank(type)) {
type = TYPE_PHASE;
}
res = pDFPrintHelper.createPDF(id, html,json);
file = (File) res[0];
if (res[1] != null) {
errors+= res[1];
}
if (StringUtils.isNotBlank(errors)) {
resp.sendError(500, errors);
}
model.addAttribute("errors",errors);
dir = pDFPrintHelper.getTemplateDir(type, id);
inputStream = new FileInputStream(file);
byte[] bytes = IOUtils.toByteArray(inputStream);
String mineType = URLConnection.getFileNameMap().getContentTypeFor(file.getName());
if (mineType == null) {
mineType = "application/octet-stream";
}
String fileName = URLEncoder.encode(file.getName(), "UTF-8");
fileName = fileName.replaceAll("\\+", " ");
resp.setContentType(mineType);
resp.addHeader("Content-Disposition", "attachment; filename=\"Print_" + fileName + "\"");
outputStream = resp.getOutputStream();
outputStream.write(bytes);
} catch (Exception e) {
log.error(e.toString());
StackTraceElement[] sts = e.getStackTrace();
for (StackTraceElement stackTraceElement : sts) {
log.warn(stackTraceElement.toString());
}
resp.sendError(404, e.toString());
} finally {
if (inputStream != null)
inputStream.close();
if (file != null && file.exists()) {
file.delete();
}
if (dir != null && dir.exists()) {
FileUtils.deleteDirectory(dir);
}
if (outputStream != null)
outputStream.close();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<link rel="stylesheet" href="https://codemirror.net/lib/codemirror.css">
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
.code-area {
float: left;
flex-direction: column;
width: 33%;
height: 93.5vh;
border: 1px solid #555;
}
.CodeMirror {
float: left;
resize: none;
outline: none;
width: 100%;
height: 94vh;
font-size: 18px;
padding: 10px;
}
.preview-area {
float: left;
width: 34%;
height: 94vh;
display: flex;
border: 1px solid #555;
}
.preview-area iframe {
width: 100%;
height: 100%;
border: none;
}
</style>
</head>
<body>
## <form action="/secure/configPDF/export.jspa" enctype="multipart/form-data">
<!-- <div class="container-fluid"> -->
<ul class="nav" style="margin-top: 1vh;">
<li class="nav-item">
<input type="submit" class="btn btn-primary" value="In PDF" onclick="printPDF()" />
</li>
<li class="nav-item">
<input type="button" class="btn btn-primary" value="Lưu template"
onclick="download(editor.getValue(),'template.vm','text/plain')">
</li>
<li class="nav-item">
<label class="btn btn-primary">
Chèn template <input type="file" hidden name="fileTemPlate" id="fileTemPlate"
onchange="loadTemplate()" />
</label>
</li>
<li class="nav-item">
<input type="button" class="btn btn-primary" value="Lưu data"
onclick="download(editor2.getValue(),'data.json','text/plain')">
</li>
<li class="nav-item">
<label class="btn btn-primary">
Chèn data <input type="file" hidden name="fileData" id="fileData" onchange="loadData()" />
</label>
</li>
<li>
<div class="input-group">
<div class="input-group has-validation"></div>
<input type="number" class="form-control" name="id" id="idPhase" placeholder="id phase">
<div class="input-group-prepend">
<span class="input-group-text" id="">ID phase</span>
</div>
</div>
</div>
</li>
<li>$!errors</li>
</ul>
<!-- </div> -->
<div class="code-area">
<textarea id="htmlCode" name="htmlLayout" placeholder="Html Code"></textarea>
</div>
<div class="preview-area">
<iframe id="preview-window" name="pdfResult"></iframe>
</div>
<div class="code-area">
<textarea id="jsonCode" name="jsonData" placeholder="Html Code"></textarea>
</div>
## </form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
<script src="https://codemirror.net/lib/codemirror.js"></script>
<script src="https://codemirror.net/mode/xml/xml.js"></script>
<script type="text/javascript">
function printPDF(){
let html= editor.getValue();
let json = editor2.getValue();
let id = $('#idPhase').val();
jQuery.ajax({
url:'/secure/configPDF/export.jspa',
type:'get',
datatype:'json',
data:{
html:html,
json:json,
id:id
},
success: function (data){
var req = new XMLHttpRequest();
req.send("GET",'/secure/configPDF/export.jspa',true)
}
});
}
var editor = CodeMirror.fromTextArea(document.getElementById("htmlCode"), {
lineNumbers: true
});
var editor2 = CodeMirror.fromTextArea(document.getElementById("jsonCode"), {
lineNumbers: true,
mode: 'application/json'
});
editor.on('change', editor => {
var frame = document.getElementById("preview-window").contentWindow.document;
frame.open();
frame.write(editor.getValue());
frame.close();
});
function loadTemplate() {
let fileToLoad = document.getElementById("fileTemPlate").files[0];
document.getElementById("fileTemPlate").value = "";
var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent) {
var textFromFileLoaded = fileLoadedEvent.target.result;
editor.setValue(textFromFileLoaded);
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
function loadData() {
let fileToLoad2 = document.getElementById("fileData").files[0];
document.getElementById("fileData").value = "";
var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent) {
var textFromFileLoaded = fileLoadedEvent.target.result;
editor2.setValue(textFromFileLoaded);
// showPreview();
};
fileReader.readAsText(fileToLoad2, "UTF-8");
}
function download(data, filename, type) {
var file = new Blob([data], { type: type });
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // Others
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
</script>
</body>
</html>
暂无答案!
目前还没有任何答案,快来回答吧!