SpringMVC file upload & file download & multiple file upload---detailed introduction

Table of contents

Foreword:

1. File upload

1.1 Add dependencies

1.2 Configuration file upload parser

1.3 Form settings

1.4 Implementation of file upload

2. File download

controller layer

 Front-end jsp

3. Multiple file upload

Controller layer

run


Foreword:

    Spring MVC is a Java-based Web framework that provides convenient file upload and download functions, as well as the ability to support multiple file uploads. The following is an explanation and examples of the detailed concepts of file upload, file download and multi-file upload as well as the convenient benefits they bring to us.

1. File upload

This article is based on the previous article to implement the addition, deletion, modification and query (CURD) http://t.csdn.cn/tFC6m to expand and implement a series of operations such as file uploading.


File upload refers to the process of transferring local files to the server . In web development, file upload is often used by users to submit pictures, documents and other files to the server for subsequent processing or storage.

Case:

1.1 Add dependencies

  If you have implemented the pom.xml dependency of the blogger’s previous article, it may have been imported. You can check it again.

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

1.2 Configuration file upload parser


<!--在spring-mvc.xml文件中添加文件上传解析器。-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>

1.3 Form settings

Define a jsp page

The form submission method is method="post" and enctype="multipart/form-data"

<form action="${ctx}/clz/upload" method="post" enctype="multipart/form-data">
    <label>班级编号:</label><input type="text" name="bid" readonly="readonly" value="${param.cid}"/><br/>
    <label>班级图片:</label><input type="file" name="xxx"/><br/>
    <input type="submit" value="上传图片"/>
</form>

1.4 Implementation of file upload

In one sentence: Where do files come from (read stream) and where do they go (write stream).

In order to make the code more standardized and concise, we put the uploaded image storage address and network access address into a file and call it at the controller layer.

Create a file named resource.properties:

The server above is the address of the image.

  • controller layer

//文件上传下载
    @RequestMapping("/upload")//映射路径
    public String upload(Tbook tbook,MultipartFile xxx){
        try {
        //上传图片存储地址
        String dir= PropertiesUtil.getValue("dir");
        //网络访问地址
        String server =PropertiesUtil.getValue("server");
        String filename=xxx.getOriginalFilename();
        System.out.println("文件名:"+filename);
        System.out.println("文件类型"+xxx.getContentType());
            FileUtils.copyInputStreamToFile(xxx.getInputStream(),new File(dir+filename));

       //相当于某一张图片的访问地址  保存到数据库中
       tbook.setBname(server+filename);

       tbookBiz.updateByPrimaryKeySelective(tbook);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:list";
    }

Front-end jsp writing:

operation result:

After successful operation, modify the network address book/list. Click on the picture upload to select a picture and click to upload the picture. The corresponding picture will be displayed at the corresponding number.

2. File download

Add a method in the controller layer and comment in the method //The code below the download key code may be used to download images in the future, and they are all fixed codes. Just copy it directly and improve efficiency

controller layer

@RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(Tbook tbook,HttpServletRequest req){

        try {
            //先根据文件id查询对应图片信息
            Tbook clz = this.tbookBiz.selectByPrimaryKey(tbook.getBid());
            String diskPath = PropertiesUtil.getValue("dir");
            String reqPath = PropertiesUtil.getValue("server");
            String realPath = clz.getBname().replace(reqPath,diskPath);
            String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
            //下载关键代码
            File file=new File(realPath);
            HttpHeaders headers = new HttpHeaders();//http头信息
            String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

 Front-end jsp

<a href="${pageContext.request.contextPath }/book/download?bid=${b.bid}">图片下载</a>

operation result:

After successful operation, modify the network address book/list and click on the image download to download the image.

3. Multiple file upload

Save multiple files to a specified storage folder

Controller layer

 //多文件上传
    @RequestMapping("/uploads")
    public String uploads(HttpServletRequest req, Tbook Tbook, MultipartFile[] files){
        try {
            StringBuffer sb = new StringBuffer();
            for (MultipartFile cfile : files) {
                //思路:
                //1) 将上传图片保存到服务器中的指定位置
                String dir = PropertiesUtil.getValue("dir");
                String server = PropertiesUtil.getValue("server");
                String filename = cfile.getOriginalFilename();
                FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));
                sb.append(filename).append(",");
            }
            System.out.println(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:list";
    }

run

Guess you like

Origin blog.csdn.net/m0_73192864/article/details/132776844