简介: 在实际工作中我们经常会遇到下载服务器中的文件到本地和上传文件到服务器的需求,下面我们来看一下具体怎么实现(直接贴代码)
下载文件
- 后台代码:
public void download(HttpServletResponse response) {
try {
String path = "想要下载的文件地址";
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));//解决中文乱码问题
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
- 前台代码:
<div class="layui-input-block">
<button type="button" class="layui-btn layui-btn-warm" id="download"><i class="layui-icon"></i>下载模板</button>
</div>
//下载模板
$("#download").click(function () {
var form=$("<form>"); // 定义一个form表单
form.attr("style","display:none");
form.attr("target","_self");
form.attr("method","post");
form.attr("action","/excel/download"); // 此处填写文件下载提交路径
var input=$("<input>");
input.attr("type","hidden");
$("body").append(form); // 将表单放置在web中
form.append(input);
form.submit(); // 表单提交
});
上传文件
- 前台代码
<button type="button" class="layui-btn" id="upload"><i class="layui-icon"></i>上传模板</button>
<span style="padding: 0 10px;color: #999;" id="lastName"></span>
//上传Excel文件
upload.render({
elem: '#upload'
, url: '/excel/upload' //改成您自己的上传接口
, accept: 'file' //普通文件
, acceptMime: 'file/*'
, exts: 'xlsx|xls'
, size: 5000
//,multiple: true
,done: function(res){
layer.msg('上传成功');
if (res.code = 2000) {
$("#filePath").val(res.data);
$("#lastName").text(res.msg);
}
}
});
- 后台代码
@RequestMapping("upload")
public Results upload(@RequestParam("file") MultipartFile file ) {
String filePath = "文件存储路径";
//文件存储路径
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try (FileOutputStream out = new FileOutputStream(filePath + file.getOriginalFilename());) {
out.write(file.getBytes());
} catch (Exception e) {
e.printStackTrace();
return Results.error("文件上传失败!");
}
return Results.success(file.getOriginalFilename(),file.getOriginalFilename());//返回文件上传路径
}