文件上传:
前端代码就是和html标签<input type="file" id="fileinput"/>
js:
upload:function () {
if($("#fileinput")[0].files[0] == undefined){
$('#tip').html('请选择文件');return;//自定义显示区域
}
// 准备FormData
var fd = new FormData();
fd.append("fileinput", $("#fileinput")[0].files[0]);
// 创建xhr对象
var xhr = new XMLHttpRequest();
// 监听状态,实时响应
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var percent = Math.round(event.loaded * event.total);
console.log('%d%', percent);
}
};
// 传输开始事件
xhr.onloadstart = function(event) {
//停止上传
$("#stopbtn").one('click', function() {
xhr.abort();
$(this).hide();
});
vm.loading(true);
};
// ajax过程成功完成事件
xhr.onload = function(event) {
//文件上传成功后,提示 xhr.responseText
$('#tip').html(xhr.responseText);//自定义显示区域
};
// ajax过程发生错误事件
xhr.onerror = function(event) {
$('#tip').html('发生错误');//自定义显示区域
};
// ajax被取消
xhr.onabort = function(event) {
// $("#upprog").text('操作被取消');
};
// loadend传输结束,不管成功失败都会被触发
xhr.onloadend = function (event) {
vm.loading(false);
};
// 发起ajax请求传送数据 请求url :budgetAssessManagement/public/uploadbudgetAssessManagement/public/upload'budgetAssessManagement/public/upload'budgetAssessManagement/public/upload'budgetAssessManagement/public/upload'budgetAssessManagement/public/uploadbudgetAssessManagement/public/uploadbudgetAssessManagement/public/upload'/budgetAssessManagement/public/upload'/budgetAssessManagement/public/upload
xhr.open('POST', '/budgetAssessManagement/public/upload', true);
xhr.send(fd);
},
addToFlist:function(fname) {
var temp = ["<p id='" + fname + "'>",
fname,
"<button onclick='delFile(\"" + fname+ "\");'>删除</button>",
"</p>"
];
$("#flist").append(temp.join(""));
},
delFile:function(fname){
console.log('to delete file: ' + fname);
},
loading:function(showloading) {
if (showloading) {
$("#uptxt").show();
$("#stopbtn").show();
} else {
$("#uptxt").hide();
$("#stopbtn").hide();
}
},
后台代码:
public void fileUpload(HttpServletRequest request,HttpServletResponse response) throws IOException {
System.out.println("开始");
//获取上传路径 字符串拼接 String.format效率好些 一般就是直接+ 或是使用StringBuilder或StringBuffer接
String p= String.format("%s\\upload\\", request.getSession().getServletContext().getRealPath(File.separator));
if(p.indexOf("ROOT"+File.separator)>0||p.indexOf("root"+File.separator)>0){
p = p.replace("ROOT"+File.separator,"");
}
response.addHeader("x-frame-options","DENY");
response.addHeader("x-frame-options","SAMEORIGIN");
Long returnl = null;
if (request instanceof MultipartHttpServletRequest) {
//获取 InputStream
MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
Iterator iter = mr.getFileMap().values().iterator();
if (iter.hasNext()) {
MultipartFile file = (MultipartFile) iter.next();
//获取文件名
String oname = file.getOriginalFilename().replace(File.separator,"");
//文件保存路劲
String uploadRootPath =p;
//保存的文件绝对路径
String uploadName =uploadRootPath +System.currentTimeMillis()+oname;
//判断这个文件夹是否存在,如果不存在则创建
File files = new File(uploadRootPath);
if(!files.exists()){
files.mkdir();
}
//文件放入到InputStream里面去,然后用OutputStream写入到文件
InputStream is = file.getInputStream();
OutputStream os = null;
try{
os = new BufferedOutputStream(
new FileOutputStream(uploadName));
byte[] buffer = new byte[1024*1024];
int bytelen = 0;
while((bytelen = is.read(buffer))>0){
os.write(buffer, 0, bytelen);
}
}finally{
if(is!=null)is.close();
if(os!=null)os.close();
}
}
}
}
文件下载:
前端代码:使用的a标签href的属性请求后台或是使用js写window.location.href=""请求后路径,至于保存的路径就交于浏览器的弹出提 (注意理解)
后台代码:
private static void downFileLoad(HttpServletRequest request,
HttpServletResponse response, String fileName, String filePath
) throws Exception {
File file = new File(filePath);// path是源文件的路径
String filename =fileName;// 源文件的名称
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
os.write(buffer);// 输出文件
os.flush();
os.close();
}