SpringMVC-----实战(用户注册头像上传和文件下载)

一.头像上传核心代码

register.jsp中的form表单提交注意修改:    enctype="multipart/form-data"

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
	$(function(){
		var username=false;
		var password=false;
		var passwordSure=false;
		/* 用户名验证 */
		$(":text:eq(0)").blur(function(){
			if($(this).val()==""){
				$(this).next().css("color","red").html("X");
				username=false;
			}else{
				$(this).next().css("color","green").html("√");
				username=true;
			}
			
		});
		/* 密码验证 */
		$(":password:eq(0)").blur(function(){
			//在js中要求正则两侧必须有"//"    jdk中pattern可查看正则表达式相关规则
			if(!$(this).val().match(/^\w{6,12}$/)){
				$(this).next().css("color","red").html("X");
				password=false;
			}else{
				$(this).next().css("color","green").html("√");
				password=true;
			}
		});
		//确认密码
		$(":password:eq(1)").blur(function(){
			if($(this).val()==""||$(this).val()!=$(":password:eq(0)").val()){
				$(this).next().css("color","red").html("X");
				passwordSure=false;
			}else{
				$(this).next().css("color","green").html("√");
				passwordSure=true;
			}
		});
		//文件上传
		$(":submit").click(function(){
			//alert($(":file:eq(0)").val());
			if(username==false||password==false||passwordSure==false||$(":file:eq(0)").val()==""){
				alert("请添写完整信息");
				return false;
			}
		});
		
	});
</script>
</head>
<body>
<form action="register" method="post" enctype="multipart/form-data">
	用户名: <input type="text" name="username"/><span></span><br>
	密码: <input type="password" name="password"/><span></span><br>
	确认密码: <input type="password" name="passwordSure"/><span></span><br>
	头像: <input type="file" name="file"/><br>
	<input type="submit"  value="注册">
</form>
</body>
</html>

UsersController.java中接收浏览器上传文件并存储

package com.kennosaur.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.kennosaur.pojo.Users;
import com.kennosaur.service.UsersService;

@Controller
public class UsersController {
	@Resource
	private UsersService usersServiceImpl;
	
	@RequestMapping("register")
	public String register(Users users,MultipartFile file,HttpServletRequest req) {
		String fileName = UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String path = req.getServletContext().getRealPath("images")+"\\"+fileName;
		System.out.println(path);
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path));
		} catch (IOException e) {
			e.printStackTrace();
		}
		users.setPhoto(fileName);
		int index = usersServiceImpl.insRegister(users);
		if (index>0) {
			req.getSession().setAttribute("user", users);
			return "redirect:/show";
		}else {
			return "redirect: /register.jsp";
		}
	}
}

二.文件下载

main.jsp请求

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
	$(function(){
		$("a").click(function(){
			var $td = $(this).parent().prev();
			$td.html(parseInt($td.html())+1);
		})
	})
</script>
</head>
<body>
<table border="1">
	<tr>
		<td>资料名称</td>
		<td>下载次数</td>
		<td>操作</td>
	</tr>
	<c:forEach items="${list }" var="file">
		<tr>
			<td>${file.name }</td>
			<td>${file.count }</td>
			<td><a href="download?id=${file.id}&name=${file.name}">下载</a></td>
		</tr>
	</c:forEach>
</table>
</body>
</html>

FilesController.java

res.setHeader("Content-Disposition", "attachment;filename="+name);

package com.kennosaur.controller;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kennosaur.pojo.Users;
import com.kennosaur.service.FilesService;

@Controller
public class FilesController {
	@Resource
	private FilesService filesServiceImpl;
	@RequestMapping("show")
	public String show(Model model) {
		model.addAttribute("list", filesServiceImpl.show());
		return "main.jsp";
	}
	@RequestMapping("download")
	public void download(int id, String name,HttpServletResponse res,HttpServletRequest req) throws IOException {
		filesServiceImpl.updCount(id, (Users)req.getSession().getAttribute("user"), name);
		res.setHeader("Content-Disposition", "attachment;filename="+name);
		ServletOutputStream os = res.getOutputStream();
		File file = new File(req.getServletContext().getRealPath("files"),name);
		os.write(FileUtils.readFileToByteArray(file));
		os.flush();
		os.close();
	}
}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值