美文网首页程序员Spring Boot
SpringBoot进行文件上传(一)

SpringBoot进行文件上传(一)

作者: OnyWang | 来源:发表于2018-02-26 09:28 被阅读3521次

扫盲

首先,必须明确几个问题:

  • 如果是ajax进行表单提交或者数据请求,就不要考虑文件上传的问题了。ajax做的是数据提交,压根就不能进行文件的输出。
  • 文件上传,必须注意一下请求类型,需要是文件请求并且必须是POST形式。参照:
<form id="baseForm"  action="/admin/saveOrUpdatePageInfo" class="form-horizontal" role="form"
                      enctype="multipart/form-data" method="post">

注意:两个属性enctype和method,其中method记得一定指定一下post。

实现过程

后台业务实现

@RequestMapping("saveOrUpdatePageInfo")
    public String saveOrUpdatePageInfo(ModelMap model,@RequestParam("file") MultipartFile file, PageInfo pageInfo,HttpServletRequest request){
        //首先进行文件上传
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        /*System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);*/
//        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
//        String filePath = location+"/"+fileName;
        try {
            FileUtil.uploadFile(file.getBytes(), location, fileName);
        } catch (Exception e) {
            // TODO: handle exception
            return "1";
        }
        pageInfo.setUrl(fileName);
        //查询业务编号是否存在
        PageInfo samePageInfo = pageInfoService.selectByName(pageInfo.getName());
        if(samePageInfo!=null){
            return "1";
        }else{
            pageInfoService.saveOrUpdate(pageInfo);

        }

        return toPageSetting(model,request);
    }

以上需要注意文件元素的传入:使用RequestParam注解进行该元素的传入操作@RequestParam("file") MultipartFile file,其中file表示html页面中文件对应的name标签值。

文件上传

/**
     * 上传文件
     * @param file  文件对应的byte数组流   使用file.getBytes()方法可以获取
     * @param filePath  上传文件路径,不包含文件名
     * @param fileName 上传文件名
     * @throws Exception
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+"/"+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

页面设计

<form id="baseForm"  action="/admin/saveOrUpdatePageInfo" class="form-horizontal" role="form"
                      enctype="multipart/form-data" method="post">
                    <div class="form-group">
                        <label class="col-md-2 control-label">资源名称</label>
                        <div class="col-md-10">
                            <input type="text" class="form-control" name="name">
                        </div>
                    </div>
</form>

上传文件路径

以上实现了文件的上传过程,但是我们使用springboot进行开发过程中,最终打包生成的是一个jar包。那么问题来了,文件上传到了什么地方呢?大家知道,jar包启动的时候,会默认生成一个tomcat运行文件夹。上传到该文件夹下面明显是不合适的,因为每次运行jar包都会新生成一遍。那么,之前上传的文件都不存在了,明显不是我们期望的结果。
如何去指定一个文件夹作为默认的文件上传路径呢?
配置文件配置如下:

img.location = d:/mypicture
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:${img.location}

我们使用@Value标签获取到文件上传路径。之后将路径传入到上传文件的方法里面。

 @Value("${img.location}")
  private String location;

FileUtil.uploadFile(file.getBytes(), location, fileName);

以上,完成了一个指定文件路径上传的功能。

静态资源访问

上传文件完成之后,就可以进行图片的访问了。但是,对于springboot而言,已经对请求进行了拦截。并且,假如是绝对路径的话,该图片是存在于服务端的,服务端下的某个绝对地址,如何从客户端进行访问?
配置文件配置如下:

img.location = d:/mypicture
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:${img.location}

什么意思呢?我们指定了一个静态资源,并且指定所有的请求都会经过该静态资源的过滤。假如此时我请求一个资源,比如localhost:8080/test.jpg。我们就会对该路径进行拦截,拦截之后做什么呢?会去spring.resources.static-locations对应的路径下面查找该资源。当然,如果配置多个的话,会进行路径的逐个查询。此时,会从d:/mypicture下满查找test.jpg。找到之后,就进行了资源的显示。

以上,即为简单的基于springboot的文件上传说明。

相关文章

网友评论

    本文标题:SpringBoot进行文件上传(一)

    本文链接:https://www.haomeiwen.com/subject/ttgsxftx.html