网页上传下载图片

文件上传
1、创建文件或图片的指定路径,包含静态资源
webapp/static/images

2、前端代码(仅供参考)
<%–图片上传–%>

传入后台参数类型MultipartFile file 3、后台代码 Controller类中上传方法参数:MultipartFile file,HttpServletRequest request if(file.isEmpty()){ System.out.println("上传文件不能为空"); logger.warn("上传文件不能为空"); } //获取项目名全路径 打印查看路径 String projectPath = request.getServletContext().getRealPath(""); //获取文件名 String filename = file.getOriginalFilename(); //固定路径常量 final String filePath = "static\\images\\"; //拼接完整文件路径 打印查看路径 String realPath = projectPath + filePath +filename; //生成上传路径对象 File upload = new File(projectPath +filePath); //文件上传 try{ //如果目录不存在,就创建该路径 if(!upload.exists()){ upload.mkdirs(); } file.transferTo(new File(realPath)); }catch (IOException e){ e.printStackTrace(); }

文件下载
1、前端代码(仅供参考)
图片添加下载链接



2、后端代码
//设置下载文件MIME类型
response.setContentType(request.getServletContext().getMimeType(fileName));
//设置下载后文件名
response.setHeader(“Content-Disposition”,“attachment;filename=”+fileName);
//获取目标文件的绝对路径
String fullFileName = request.getServletContext().getRealPath("/"+“static\images\”+fileName);//imagePath
//读取文件
InputStream in = new FileInputStream(fullFileName);
OutputStream out = response.getOutputStream();
//写文件
byte[] bytes = new byte[1024];
//初始下载长度
int length = 0;
while((length = in.read(bytes))!= -1){
out.write(bytes,0,length);
}
in.close();
out.close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值