SpringMVC创建web项目基础之(三)——Spring MVC实现文件上传

来源:互联网 发布:红鸟棋牌游戏源码 编辑:程序博客网 时间:2024/06/08 13:35

有时候,最美的惊喜并不是得到,而是学会付出。——《 安娜和她的云 》

最近放慢了写作的速度,是因为我慢慢觉得有些东西还是沉淀一段时间后才会更有价值。

我们先来看看使用Spring MVC实现文件上传所需要的jar包

?
1
2
3
4
5
6
7
8
9
10
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

这里只列出了上传下载所需要的jar包,使用Spring MVC框架的jar包我在上一篇文章已经写过了,如果还没看的请点击链接springmvc创建web项目基础之二-spring-mvc与mybatis整合详解先去看我的上一篇文章。

一、前端页面实现

前端页面很简单,样子如下:

springMVC_upload_1

<div class="col-lg-12" style="margin-top: 10px"><form id="upLoad_form" method="post" enctype="multipart/form-data"> <input type="file" id="picture" name="file"> <button  type="button" id="upload_btn" class="btn btn-primary" >上传图片</button></form></div>


?

二、后端实现

1.控制器BookShopController

在这个项目里简单实现一个上传图片的功能。

?
 
@Resourceprivate BookShopService mService;/**     * 上传图片     *      * @param MultipartFile file 页面选中的文件     * @param HttpServletRequest request 请求     * @param HttpServletResponse response 响应     *      */    @RequestMapping(value = "/upload", method = RequestMethod.POST)      @ResponseBody    public void upload(@RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response) {          try {    mService.uploadFile(file,request,response);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}    }  

2.服务接口BookShopService

public interface BookShopService {public void uploadFile(MultipartFile file,HttpServletRequest request, HttpServletResponse response) throws Exception;}

?

3.服务接口的实现类BookShopServiceImpl

@Servicepublic class BookShopServiceImpl implements BookShopService {@Overridepublic void uploadFile(MultipartFile file,HttpServletRequest request, HttpServletResponse response) throws Exception {BookShopUploadUtil.fileUp(file,request,response);}}


?

4.上传文件工具类BookShopUploadUtil

这个是实现上传文件的核心实现

public class BookShopUploadUtil {/**     * 上传图片     */    public static void fileUp(MultipartFile file,HttpServletRequest request,            HttpServletResponse response) throws Exception {     String path="";//保存图片路径     String filePath = Consts.CONTEXTPATH;//显示图片路径(相对路径)     try {             if (!file.isEmpty()){                              //得到服务器中保存文件的绝对路径             path = request.getServletContext().getRealPath(Consts.SAVE_PATH + "/");                 //新建文件夹             newFolder(path);             //新建文件夹完成后将路径添加文件名             path += file.getOriginalFilename();             //页面显示图片的相对路径             filePath += "/" + Consts.SAVE_PATH +  "/" + file.getOriginalFilename();             //使用StreamsAPI方式拷贝文件             Streams.copy(file.getInputStream(),new FileOutputStream(path),true);             //将上面得到的图片相对路径返回给页面          JSONObject json = new JSONObject();             json.accumulate(Consts.SRC, filePath);  json.accumulate("error", false);          json.accumulate("message", "上传成功!");          PrintWriter out = response.getWriter();          out.print(json.toString());          out.flush();          out.close();             }         } catch (Exception e) {             System.out.println("文件上传失败");             e.printStackTrace();             path="";         }    }/**     * 创建文件夹     *      * @param folderPath     */    public static void newFolder(String folderPath) {        try {            File myFilePath = new File(folderPath);            if (!myFilePath.exists()) {            //创建多级文件夹                myFilePath.mkdirs();                System.out.println("创建文件夹路径:" + folderPath);            }        } catch (Exception e) {            System.out.println("新建文件夹操作出错");            e.printStackTrace();        }    }}
?

Consts.SAVE_PATH是一个字符串常量,表示存放路径

public class Consts { public final static String SRC = "src"; public final static String SAVE_PATH = "resources/bookshopupload/savefile/";  }
?

至此实现就完成了,效果如下

springMVC_upload_2

如果你喜欢我的文章请扫描主页的微信公众号二维码,每天都有新推文。

如果你喜欢我的文章请收藏我的个人网站:http://www.bubblyyi.com

1 0
原创粉丝点击