Maven工程上传文件(速成)

一、打开Idea新建Maven工程,工程目录如下

二、配置pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zhangsan</groupId>
  <artifactId>project</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>project Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.26</version>
  </dependency>


    <!--文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.5</version>
    </dependency>
  </dependencies>



  <build>
    <finalName>project</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>8</source>
          <target>8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

三、配置spring-mvc.xml文件

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.zl.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSizePerFile" value="100001000"></property>
    </bean>

</beans>

四、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">


  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

五、编写FileUpAownLoadController.java类

package com.zl.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;


@Controller
public class FileUpDownLoadController {
    public static String FILE_PATH = "C:/WEB/";


    @RequestMapping("/fileup")
    public String File(){
        return "FileUpLoad";
    }
    /**
     * 单文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/fileUpload")
    public String fileUpload(MultipartFile file) throws IOException {
        String path = FILE_PATH;
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdirs();
        }

        if (null != file && !file.isEmpty()){
            String originalFilename = file.getOriginalFilename();
            UUID uuid = UUID.randomUUID();
            String fileName = uuid + "_" + originalFilename;
            file.transferTo( new File(path + fileName)  );
            return "success";
        }

        return "success";
    }

    /**
     * 多文件上传
     */
    @RequestMapping("/multiFileUpload")
    public String multiFileUpload(MultipartFile[]  files) throws IOException {
        String path = FILE_PATH;
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdirs();
        }

        if (null!=files && files.length> 0){
            for(MultipartFile file : files){
                if (!file.isEmpty()){
                    String originalFilename = file.getOriginalFilename();
                    UUID uuid = UUID.randomUUID();
                    String fileName = uuid +"_"+ originalFilename;

                    file.transferTo(new File(path + fileName ));
                }
            }
            return "success";
        }
        return "success";
    }

    /**
     * 文件下载
     */
    @RequestMapping("/fileDownload")
    public ResponseEntity<byte[]> fileDownload() throws Exception {
        String path = FILE_PATH;
        String fileName = "tiangong01.jpeg";
        String desfileName = new String(fileName.getBytes(StandardCharsets.UTF_8),"iso8859-1");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",desfileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        ResponseEntity<byte[]> responseEntity =
                new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(path+fileName)),headers,HttpStatus.OK);
        return responseEntity;
    }
}

 六、编写FileUpLoad.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

</head>
<body>
        <h1>文件上传页面</h1>

        <fieldset>
            <legend>单文件上传</legend>
            <form action="${pageContext.request.contextPath }/fileUpload" method="post" enctype="multipart/form-data">

                请选择文件: <input type="file" name="file" id="fileToUpload"><br><br>
                <input type="submit" value="开始上传">
            </form>
        </fieldset>
        <br>
        <br>
        <br>


        <fieldset>
            <legend>多文件上传</legend>
            <form action="${pageContext.request.contextPath }/multiFileUpload"
                  method="post" enctype="multipart/form-data">

                请选择文件: <input type="file" name="files" multiple ><br><br>
                <input type="submit" value="多文件开始上传">
            </form>
        </fieldset>
        <br>
        <br>
        <br>
</body>
</html>

 

七、在pages新建一个success.jsp文件,如图

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
上传成功!!!
</body>
</html>

八、配置tomcat

九、直接启动

然后点击浏览,选择文件

这样就上传成功啦!我们只需要找到自己设置的保存路径下就可以查看我们上传的文件啦!

小伙伴们赶紧run起来来吧!!!欢迎留言哦!制作不易,给个赞吧!!!嘻嘻

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值