springmvc 上传文件

来源:互联网 发布:mysql查看表空间剩余 编辑:程序博客网 时间:2024/06/02 18:51

最近在做一个上传用户头像的接口,上传图片或者文本文件都可以的。
接下来我弄了一个测试的接口来还原这个接口的实现。

接口功能说明:
1、接收文件
2、更改文件名
3、获取文件请求地址
4、保存到本项目的静态文件目录中。
5、将文件请求地址保存到数据库。

直接贴代码:

/***跳转页面的方法*/@RequestMapping(value = "/upload",method=RequestMethod.GET)      public String uploadget() {        return "index";    }    @RequestMapping(value = "/upload")      public @ResponseBody Message upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {        /**         * 从数据库查出用户名为ming的用户信息         */        User user = iUserService.getUserByAccessname("ming");        /**         * 文件保存至服务器的文件夹地址         */        String path =request.getSession().getServletContext().getRealPath("/")+"\\WEB-INF\\resources\\header";        /**         * 获得文件名         */        String file_name = file.getOriginalFilename();        /**         * 截取文件后缀名,如jpg,gif         */        String suffix = file_name.substring(file_name.lastIndexOf(".") + 1);        /**         * 拼接文件名         */        String fileName = user.getUsername()+new Date().getTime()+"."+suffix;          /**         * 图片链接地址,保存到数据库的地址         */        String request_path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/resources/header";        String pic_path = request_path+"/"+fileName;        /**         * 下载图片到服务器文件夹         */        File targetFile = new File(path,fileName);        /**         * 如果没有该文件夹,就创建文件夹         */        if(!targetFile.exists()){              targetFile.mkdirs();          }          try {              /**             * 保存文件到项目本地文件夹             */           file.transferTo(targetFile);              /**             * 修改用户头像地址             */            User _user = iUserService.getUserById(user.getId());            _user.setUri_pic(pic_path);            boolean result = iUserService.updateuUser(_user);            return new Message(200, be.OptSuccess, pic_path, targetFile.getAbsolutePath(), null, null);        } catch (Exception e) {              e.printStackTrace();            return new Message(400, be.Exception, null, null, null, null);        }    }

测试页面,上传头像
测试页面

测试页面代码:

<div><form action="../l/upload" method="post" >      <input type="file" name="file" />    <input type="submit" value="Submit" /></form>  </div>

生成的保存到数据库的图片地址:
http://localhost:8081/test/resources/header/ming81503049445037.gif
在浏览器输入,可以查看图片
这里写图片描述