[SpringMVC] File upload and download, JREBEL use

Table of contents

I. Introduction

2. File upload

1. Single file upload

1.1. Data table preparation

1.2. Add dependencies

1.3. Configuration file

1.4. Writing forms

1.5. Write the controller layer

2. Multiple file upload

2.1. Write form form

2.2. Write the controller layer

2.3. Testing

3. File download

4. Use of JREBEL

1. Download and register

2. Offline settings


I. Introduction

Why use file upload and download? effect?

SpringMVC file upload and download is a common function , which allows users to upload files to the server or download files from the server. This is an essential feature for many web applications, such as online storage, document management systems, etc. SpringMVC provides some convenient annotations and APIs that make file uploading and downloading very simple. In terms of file upload, SpringMVC provides @RequestParam annotation and MultipartFile class to easily handle uploaded files. In terms of file downloading, SpringMVC provides the ResponseEntity class, which can send files to the client as a response.

2. File upload

1. Single file upload

1.1. Data table preparation

It is also possible to use it according to your own table, it is just used to save data.

1.2. Add dependencies

Add file upload dependencies in pom.xml in your spring mvc

<dependencies>        
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload.version}</version>
        </dependency>
</dependencies>

1.3. Configuration file

Add configuration in your own spring-mvc.xml file

<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>

Below I provide my file configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.3.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--1) 扫描com.tgq及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <context:component-scan base-package="com.tgq"/>

    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <mvc:annotation-driven/>

    <!--3) 创建ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--4) 单独处理图片、样式、js等资源 -->
    <!--        <mvc:resources location="/static/" mapping="/static/**"/>-->
    <!--    处理文件上传下载问题-->
    <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>
    <!--  处理controller层发送请求到biz,会经过切面的拦截处理  -->
    <aop:aspectj-autoproxy/>
</beans>

1.4. Writing forms

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

<%--
  Created by IntelliJ IDEA.
  User: tgq
  Date: 9/9/2023
  Time: 下午2:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图片上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/sc/upload" method="post" enctype="multipart/form-data">
    <label>编号:</label><input type="text" name="cid" readonly="readonly" value="${param.cid}"/><br/>
    <label>图片:</label><input type="file" name="zx"/><br/>
    <input type="submit" value="上传图片"/>
</form>
</body>
</html>

The name of the uploaded image cannot be the same as the column name of the database table , but it must be the same as the name of the back-end code.

1.5. Write the controller layer

@Controller
@RequestMapping("/sc")
public class StrutsClasController {

    @Autowired
    private StrutsClasBiz strutsClasBiz;

 /**
     * 文件上传
     * <p>
     * //     * @param req
     * //     * @param strutsClas
     *
     * @param zx
     * @return
     */
    @RequestMapping(value = "/upload")
    public String upload(StrutsClas strutsClas, MultipartFile zx) {
//    public String upload(HttpServletRequest req, StrutsClas strutsClas, MultipartFile pic) {
        try {
            //思路:
            //1) 将上传图片保存到服务器中的指定位置
//            本地保存地址
//            String dir = PropertiesUtil.getValue("dir");
              String dir="d:/";
//            网络保存地址/upload/
//            String server = PropertiesUtil.getValue("server");
              String server="/upload/";
//            文件名
            String filename = zx.getOriginalFilename();
//            System.out.println("文件名:" + filename);
//            文件类别
//            System.out.println("文件类别" + zx.getContentType());
            System.out.println(strutsClas);
            FileUtils.copyInputStreamToFile(zx.getInputStream(), new File(dir + filename));
            //2) 更新数据库表t_struts_class图片记录
            strutsClas.setPic(server + filename);
            strutsClasBiz.updateByPrimaryKeySelective(strutsClas);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:list";
    }
}

When configuring tomcat, remember to add upload address mapping

2. Multiple file upload

2.1. Write form form

<form method="post" action="/sc/uploads" enctype="multipart/form-data">
    <input type="file" name="files" multiple>
    <button type="submit">上传</button>
</form>

2.2. Write the controller layer

 /**
     * 多文件上传
     *
     * @param req
     * @param clas
     * @param files
     * @return
     */
    @RequestMapping("/uploads")
    public String uploads(HttpServletRequest req,MultipartFile[] files) {
        try {
            StringBuffer sb = new StringBuffer();
            for (MultipartFile cfile : files) {
                //思路:
                //1) 将上传图片保存到服务器中的指定位置
                String dir = "D:/temp/upload/";
                String server = "/upload/";
                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";
    }

2.3. Testing

But when we select multiple files to upload,

our local files are empty.


When we upload it, it will be uploaded locally

The same applies to our database

3. File download

Operate according to your own table

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

Write the controller layer method

/**
     * 文件下载
     *
     * @param strutsClas
     * @param req
     * @return
     */
    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(StrutsClas strutsClas, HttpServletRequest req) {

        try {
            //先根据文件id查询对应图片信息
            StrutsClas strutsClas1 = this.strutsClasBiz.selectByPrimaryKey(strutsClas.getCid());
//需要下载的地址
            String diskPath = PropertiesUtil.getValue("dir");
//服务器里面保存图片的地址
            String reqPath = PropertiesUtil.getValue("server");
            String realPath = strutsClas1.getPic().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;
    }

It will download when we click download

4. Use of JREBEL

1. Download and register

Search for the plug-in JRebel and download it. After successful installation, you will be asked to restart. After restarting, press the operation button.

Register in the pop-up box

Fill in http://127.0.0.1:8888/GUID in the first one    

GUID: Change to GUID and fill in the ID   generated in online erstellen

Final confirmation of registration

Start your agent. Then run JRebel

2. Offline settings

Enter our settings, the premise is that we need to start our agent to perform this operation

Guess you like

Origin blog.csdn.net/weixin_74383330/article/details/132776908