实现文件上传和数据库记录、Element+vue登录注册UI

This commit is contained in:
F嘉阳
2018-02-03 20:44:25 +08:00
parent bc720e6270
commit b9d60e644b
23 changed files with 846 additions and 24 deletions

View File

@@ -0,0 +1,94 @@
package com.fjy.spring.controller;
import com.fjy.spring.domain.TbFile;
import com.fjy.spring.enums.ResultEnum;
import com.fjy.spring.exception.UserException;
import com.fjy.spring.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
@Controller
public class DownLoadController {
@Autowired
private FileService fileService;
@GetMapping("/download")
public String toDownloadPage(){
return "download";
}
@GetMapping("/download/findall")
@ResponseBody
public List<TbFile> toDownloadAll(){
List<TbFile> files = fileService.findAllFile();//此处做空指针判断并抛出错误
if (files!=null)
return files;
new UserException(ResultEnum.EMPTY_DATA);
return null;
}
@RequestMapping("/download/dodownload")
public String download(@RequestParam String fileName , HttpServletRequest request, HttpServletResponse response){
response.setContentType("text/html;charset=utf-8");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
TbFile file = new TbFile();
file.setColfilename(fileName);
TbFile tbFile = fileService.findFile(file);
System.out.println(tbFile.getColfilepath());
String ctxPath = tbFile.getColfilepath();
String downLoadPath = ctxPath + fileName;
System.out.println(downLoadPath);
try {
long fileLength = new File(downLoadPath).length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}

View File

@@ -21,7 +21,7 @@ public class LoginController {
@PostMapping("/login/dologin")
public String doLogin(TbUser tbUser)throws Exception{
if (userService.doLoginService(tbUser.getColname(),tbUser.getColpassword())){
return "home";
return "/home/home";
}
return "login";
}

View File

@@ -0,0 +1,34 @@
package com.fjy.spring.controller;
import com.fjy.spring.domain.TbUser;
import com.fjy.spring.enums.ResultEnum;
import com.fjy.spring.exception.UserException;
import com.fjy.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;
@Controller
public class RegisterController {
@Autowired
private UserService userService;
@PostMapping(value = "/register/doregister")
public String doRegister(@Valid TbUser tbUser, BindingResult bindingResult)throws Exception{
if (bindingResult.hasErrors()){
ResultEnum resultEnum = ResultEnum.WRONG_FORM;
resultEnum.setData(bindingResult.getFieldError().getDefaultMessage());
throw new UserException(resultEnum);
}
if (userService.doRegisterService(tbUser)){
return "login";
}
throw new UserException(ResultEnum.UNKOWN_ERROR);
}
}

View File

@@ -0,0 +1,175 @@
package com.fjy.spring.controller;
import com.fjy.spring.domain.TbFile;
import com.fjy.spring.properties.ServerProperties;
import com.fjy.spring.service.FileService;
import com.fjy.spring.untils.FormatFileSizeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Controller
public class UpLoadController {
@Autowired
private ServerProperties serverProperties;//服务器配置信息
@Autowired
private FileService fileService;//文件相关数据库操作
@GetMapping("/toOneUpload")
public String toOneUpload() {
return "oneUpload";
}
@GetMapping("/toMoreUpload")
public String toMoreUpload() {
return "moreUpload";
}
/**
* 测试文件上传路径地址
*
* @param imageFile
* @param request
* @return
*/
@RequestMapping("/test")
@ResponseBody
public String testURL(@RequestParam("imageFile") MultipartFile imageFile, HttpServletRequest request) {
String uploadUrl = request.getSession().getServletContext().getRealPath("/") + "upload/";
return uploadUrl;
}
/**
* 单文件上传
*
* @param imageFile
* @param request
* @return
*/
@RequestMapping(value = "/oneUpload")
public String oneUpload(@RequestParam("imageFile") MultipartFile imageFile, HttpServletRequest request) {
String uploadUrl = request.getSession().getServletContext().getRealPath("/") + "upload/";
String filename = imageFile.getOriginalFilename();
File dir = new File(uploadUrl);
if (!dir.exists()) {//判断目录是否存在,否则自动创建
dir.mkdirs();
}
/**
* 存储文件信息
*/
TbFile file = new TbFile();
file.setColfilesize(new FormatFileSizeUtil().GetFileSize(imageFile.getSize()));
file.setColfilename(filename);
file.setColfilepath(uploadUrl + filename);
file.setColip(request.getRemoteAddr());
if (fileService.addFile(file))
System.out.println("记录写入数据库成功");
else
System.out.println("记录写入数据库失败");
System.out.println("文件上传到: " + uploadUrl + filename);
System.out.println("文件大小: " + new FormatFileSizeUtil().GetFileSize(imageFile.getSize()));
System.out.println("文件名: " + filename);
File targetFile = new File(uploadUrl + filename);
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
imageFile.transferTo(targetFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:" + request.getScheme() + "://" + request.getServerName() + ":"
+ serverProperties.getPortNum() + request.getContextPath() + "/upload/" + filename;
//return "redirect:http://localhost:8080/cms/upload/" + filename;
// return "index";
}
/**
* 多文件上传
*
* @param request
* @return
*/
@RequestMapping("/moreUpload")
public String moreUpload(HttpServletRequest request) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> files = multipartHttpServletRequest.getFileMap();
String uploadUrl = request.getSession().getServletContext().getRealPath("/") + "upload/";
File dir = new File(uploadUrl);
if (!dir.exists()) {
dir.mkdirs();
}
List<String> fileList = new ArrayList<String>();
for (MultipartFile file : files.values()) {
File targetFile = new File(uploadUrl + file.getOriginalFilename());
TbFile tbFile = new TbFile();
tbFile.setColfilesize(new FormatFileSizeUtil().GetFileSize(file.getSize()));
tbFile.setColfilename(file.getName());
tbFile.setColfilepath(uploadUrl + file.getName());
tbFile.setColip(request.getRemoteAddr());
if (fileService.addFile(tbFile))
System.out.println("记录写入数据库成功");
else
System.out.println("记录写入数据库失败");
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
file.transferTo(targetFile);
fileList.add(
request.getScheme() + "://" + request.getServerName() + ":"
+ serverProperties.getPortNum() + request.getContextPath() + "/upload/"
+ file.getOriginalFilename());
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
request.setAttribute("files", fileList);
return "moreUploadResult";
}
}

View File

@@ -0,0 +1,93 @@
package com.fjy.spring.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class TbFile {
@Id
@GeneratedValue
private int colfileid;
private int coluserid;
//private String coltime;
private String colip;
private String colrealname;
private String colfilename;
private String colfilesize;
private String colfilepath;
@Override
public String toString() {
return "TbFile{" +
"colip='" + colip + '\'' +
", colrealname='" + colrealname + '\'' +
", colfilename='" + colfilename + '\'' +
", colfilesize='" + colfilesize + '\'' +
", colfilepath='" + colfilepath + '\'' +
'}';
}
public int getColfileid() {
return colfileid;
}
public void setColfileid(int colfileid) {
this.colfileid = colfileid;
}
public int getColuserid() {
return coluserid;
}
public void setColuserid(int coluserid) {
this.coluserid = coluserid;
}
public String getColip() {
return colip;
}
public void setColip(String colip) {
this.colip = colip;
}
public String getColrealname() {
return colrealname;
}
public void setColrealname(String colrealname) {
this.colrealname = colrealname;
}
public String getColfilename() {
return colfilename;
}
public void setColfilename(String colfilename) {
this.colfilename = colfilename;
}
public String getColfilesize() {
return colfilesize;
}
public void setColfilesize(String colfilesize) {
this.colfilesize = colfilesize;
}
public String getColfilepath() {
return colfilepath;
}
public void setColfilepath(String colfilepath) {
this.colfilepath = colfilepath;
}
}

View File

@@ -2,17 +2,21 @@ package com.fjy.spring.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
@Entity
public class TbUser {
@Id
@GeneratedValue
private Integer coluserid;
@NotNull(message = "用户名必填")
private String colname;
@NotNull(message = "密码不能为空")
private String colpassword;
private String colemail;
@NotNull(message = "学号必填")
private String colstudentno;
@NotNull(message = "真实姓名必填")
private String colrealname;
public Integer getColuserid() {

View File

@@ -8,10 +8,13 @@ public enum ResultEnum {
DELETE_ERROR(103,"删除失败"),
ADD_ERROR(104,"添加失败"),
WRONGPASS(105,"用户名或密码错误"),
ILLEGAL_ACCESS(106,"非法访问")
ILLEGAL_ACCESS(106,"非法访问"),
WRONG_FORM(107,"表单错误"),
EMPTY_DATA(108,"无数据")
;
private Integer code;
private String msg;
private String data;
public Integer getCode() {
return code;
@@ -21,6 +24,15 @@ public enum ResultEnum {
return msg;
}
public void setData(String data) {
this.data = data;
}
public String getData() {
return data;
}
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;

View File

@@ -0,0 +1,18 @@
package com.fjy.spring.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "serverproperties")
public class ServerProperties {
private String portNum;
public String getPortNum() {
return portNum;
}
public void setPortNum(String portNum) {
this.portNum = portNum;
}
}

View File

@@ -0,0 +1,10 @@
package com.fjy.spring.repository;
import com.fjy.spring.domain.TbFile;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface TbFileRepository extends JpaRepository<TbFile,Integer>{
public Optional<TbFile> findByColfilename(String name);
}

View File

@@ -0,0 +1,35 @@
package com.fjy.spring.service;
import com.fjy.spring.domain.TbFile;
import com.fjy.spring.repository.TbFileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FileService {
@Autowired
private TbFileRepository tbFileRepository;
public boolean addFile(TbFile tbFile) {
TbFile file = tbFileRepository.save(tbFile);
if (file != null)
return true;
return false;
}
public TbFile findFile(TbFile tbFile){
TbFile file = (TbFile) tbFileRepository.findByColfilename(tbFile.getColfilename()).get();
if (file!=null)
return file;
return null;
}
public List<TbFile> findAllFile(){
return tbFileRepository.findAll();
}
}

View File

@@ -7,6 +7,7 @@ import com.fjy.spring.repository.TbUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@@ -16,9 +17,23 @@ public class UserService {
public boolean doLoginService(String name,String password){
TbUser user = (TbUser)tbUserRepository.findByColname(name).get();
if (password.equals(user.getColpassword())){
return true;
if (user!=null){
if (password.equals(user.getColpassword())){
return true;
}else {
throw new UserException(ResultEnum.WRONGPASS);
}
}else {
throw new UserException(ResultEnum.USER_NOTEXIST);
}
throw new UserException(ResultEnum.USER_NOTEXIST);
}
public boolean doRegisterService(TbUser tbUser){
TbUser user = tbUserRepository.save(tbUser);
if (user!=null){
throw new UserException(ResultEnum.SUCCESS);
}
return false;
}
}

View File

@@ -0,0 +1,25 @@
package com.fjy.spring.untils;
import java.text.DecimalFormat;
public class FormatFileSizeUtil {
public static String GetFileSize(long sizes){
String size = "";
if(sizes!=0){
long fileS = sizes;
DecimalFormat df = new DecimalFormat("#.00");
if (fileS < 1024) {
size = df.format((double) fileS) + "BT";
} else if (fileS < 1048576) {
size = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
size = df.format((double) fileS / 1048576) + "MB";
} else {
size = df.format((double) fileS / 1073741824) +"GB";
}
}else{
size = "非法!";
}
return size;
}
}

View File

@@ -9,4 +9,11 @@ public class ResultUtil {
result.setMessage(msg);
return result;
}
public static Result error(Integer code,String msg,Object data){
Result result = new Result();
result.setCode(code);
result.setMessage(msg);
result.setData(data);
return result;
}
}