SpringMVC普通文件上传和OSS文件上传

1.普通上传文件到本地

1.1文件上传的条件:

1.表单中。
2.表单的提交方式method必须是post.
3.表单上传的编码必须是二进制。enctype="multipart/form-data"
4.input的类型必须file类型。而且该输入框必须有name属性。

1.2前端网页:

<%--
  Created by IntelliJ IDEA.
  User: zlh
  Date: 2021/12/7
  Time: 18:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data">
    <input type="file" name="myFile"><br>
    <button>提交</button>
</form>
</body>
</html>

1.3借助第三方jar完成。 commons-fileupload(以下都需要)

<!--①文件上传的依赖-->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.4</version>
</dependency>

1.4springmvc.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"
       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
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--包扫描-->
        <context:component-scan base-package="com.aaa"/>
        <!--静态资源处理-->
        <mvc:default-servlet-handler/>
        <!--处理特殊注解-->
        <mvc:annotation-driven/>
        <!--视图解析器 前补/ 后补 .jsp-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
        <!--配置文件上传解析器-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!--设置文件上传的最大值  单位为b  不设置默认为5M-->
            <property name="maxUploadSize" value="104857600"/>
            <!--默认编码-->
            <property name="defaultEncoding" value="utf-8"/>
        </bean>
</beans>

1.5 在web.xml中注册servlet加载springmvc的配置文件(以下都需要)

<?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>
    <servlet-name>springmvc01</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc的配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>

  <!--servlet映射路径
        /: 表示所有的控制层路径 以及静态资源
        /*: 表示全部 包含jsp网页
  -->
  <servlet-mapping>
    <servlet-name>springmvc01</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

1.6后台代码

package com.aaa.controller;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @program: wen_jian_shang_chuan_145
 * @description:
 * @author: zlh
 * @create: 2021-12-07 15:00
 **/
@Controller
public class UploadController {
    @RequestMapping("/upload") //springmvc把上传的文件封装到MultipartFile类中
                                //myfile必须和前台表单中name名一直
    public String upload01(MultipartFile myFile, HttpServletRequest request){
        //获取图片在服务器下的路径 getServletContext()获取application对象也就是应用程序对象 获取当前工程对象
        // application属于ServletContext类型
        // getRealPath 获取工程下/upload文件夹的真实路径
        String path = request.getSession().getServletContext().getRealPath("/upload");
        //System.out.println(path);
        //2.根据该路径创建文件路径
        File file=new File(path);
        if (!file.exists()){//file.exists()判断指定path路径文件是否存在
            file.mkdirs();
        }
        //3.获取上传的文件名
        String originalFilename = myFile.getOriginalFilename();
        //System.out.println(originalFilename);
        //4.把上传的文件保存到目标目录
        File target=new File(path+"/"+originalFilename);

        try {
            myFile.transferTo(target);//把上传的文件保存到target目录中
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("imgsrc","http://localhost:8080/upload/"+originalFilename);
        return "success";

    }
}

2.普通文件带属性上传到本地

前台页面

<%--
  Created by IntelliJ IDEA.
  User: zlh
  Date: 2021/12/7
  Time: 14:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/up02/upload" enctype="multipart/form-data">
    <input type="file" name="myFile"><br>
    姓名<input type="text" name="name"><br>
    性别<input type="text" name="sex"><br>
    <button>提交</button>
</form>
</body>
</html>

后台代码

package com.aaa.controller;

import com.aaa.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @program: wen_jian_shang_chuan_145
 * @description:
 * @author: zlh
 * @create: 2021-12-07 15:00
 **/
@Controller
@RequestMapping("/up02")
public class UploadController02 {
    @RequestMapping("/upload") //springmvc把上传的文件封装到MultipartFile类中
                                //myfile必须和前台表单中name名一直
    public String upload01(MultipartFile myFile, HttpServletRequest request, User user){
        //获取图片在服务器下的路径 getServletContext()获取application对象也就是应用程序对象 获取当前工程对象
        // application属于ServletContext类型
        // getRealPath 获取工程下/upload文件夹的真实路径
        String path = request.getSession().getServletContext().getRealPath("/upload");
        System.out.println(user);
        //System.out.println(path);
        //2.根据该路径创建文件路径
        File file=new File(path);
        if (!file.exists()){//file.exists()判断指定path路径文件是否存在
            file.mkdirs();
        }
        //3.获取上传的文件名
        String originalFilename = myFile.getOriginalFilename();
        //System.out.println(originalFilename);
        //4.把上传的文件保存到目标目录
        File target=new File(path+"/"+originalFilename);

        try {
            myFile.transferTo(target);//把上传的文件保存到target目录中
        } catch (Exception e) {
            e.printStackTrace();
        }
        String headImg="http://localhost:8080/upload/"+originalFilename;
        request.setAttribute("imgsrc",headImg);
        user.setHeadImg(headImg);
        return "success";

    }
}

实体属性

@Data需要添加lombok的依赖包

package com.aaa.entity;

import lombok.Data;

/**
 * @program: wen_jian_shang_chuan_145
 * @description:
 * @author: zlh
 * @create: 2021-12-07 16:54
 **/
@Data
public class User {
    private String name;
    private String sex;
    private String headImg;//头像的地址
}

3.异步普通文件上传到本地

前台页面

<%--
  Created by IntelliJ IDEA.
  User: zlh
  Date: 2021/12/7
  Time: 14:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.5.1.js"></script>
</head>


<body>
<form id="userForm">
    <input type="file" name="myFile"><br>
    姓名<input type="text" name="name"><br>
    性别<input type="text" name="sex"><br>
    <input type="button" id="btn" value="提交" >
</form>
<img id="headImg">
<script>
    $("#btn").click(function (){
        var formData = new FormData(document.getElementById("userForm"));//获取表单数据
        $.ajax({
            url:"${pageContext.request.contextPath}/upload2",
            type:"post",
            contentType:false,
            processData: false,//设置表单的编码格式为二进制格式,默认true是文本格式
            dataType:"json",
            data:formData,
            success:function (result){
                if (result.code==200){
                    $("#headImg").attr("src",result.imgsrc)
                }
            }
        })
    });
</script>
</body>
</html>

后台代码

package com.aaa.controller;

import com.aaa.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: wen_jian_shang_chuan_145
 * @description:
 * @author: zlh
 * @create: 2021-12-07 18:48
 **/
@Controller
public class UploadController03 {
    @RequestMapping("/upload2")
    @ResponseBody
    public Map<String,Object> upload2(MultipartFile myFile, HttpServletRequest request, User user){
        Map<String,Object> map=new HashMap<String,Object>();
        //获取文件保存的真实路径
        String upload = request.getSession().getServletContext().getRealPath("upload");
        //根据真实路径封装文件对象
        File file=new File(upload);
        if (!file.exists()){
            file.mkdirs();
        }
        //获取文件的名称
        String filename=myFile.getOriginalFilename();
        filename=new Date().getTime()+filename;

        //文件存放在真实的路径下
        File target=new File(upload+"/"+filename);

        try {
            myFile.transferTo(target);//保存
            map.put("code",200);
            map.put("msg","上传成功");
            map.put("imgsrc","http://localhost:8080/upload/"+filename);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("code",500);
        map.put("msg","上传失败");
        return map;

    }
}

4.OSS同步上传

1创建bucket 容器。

 

 

2创建案例密钥。

 

3编写代码完成oss文件上传。

查看阿里云的OSS文档。

 

 

添加oss的依赖 (oss上传需要)

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.10.2</version>
</dependency>

前台代码

<%--
  Created by IntelliJ IDEA.
  User: zlh
  Date: 2021/12/7
  Time: 14:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/upload4" enctype="multipart/form-data">
    <input type="file" name="myFile"><br>
    姓名<input type="text" name="name"><br>
    性别<input type="text" name="sex"><br>
    <button>提交</button>
</form>
</body>
</html>

后台代码

package com.aaa.controller;

import com.aaa.entity.User;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;

/**
 * @program: wen_jian_shang_chuan_145
 * @description:
 * @author: zlh
 * @create: 2021-12-07 21:27
 **/
@Controller
public class UploadController04 {
    @RequestMapping("/upload4")
    public String upload4(MultipartFile myFile, HttpServletRequest request, User user){
        try {
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String endpoint = "oss-cn-beijing.aliyuncs.com";
            // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
            String accessKeyId = "id";
            String accessKeySecret = "密钥";

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream = myFile.getInputStream();
            //获取上传的文件名
            String filename = myFile.getOriginalFilename();
            filename = new Date().getTime() + filename;
            // 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
            ossClient.putObject("zhanglonghui", filename, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //
//            https://qy145.oss-cn-hangzhou.aliyuncs.com/16388489433231.jpg
            String url="https://zhanglonghui."+endpoint+"/"+filename;/*图片回显到前台页面*/
            request.setAttribute("imgsrc",url);
        }catch (Exception e){
            e.printStackTrace();
        }

        return "success";
    }
}

5.oss异步上传

前台代码

<%--
  Created by IntelliJ IDEA.
  User: zlh
  Date: 2021/12/7
  Time: 14:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.5.1.js"></script>
</head>


<body>
<form id="userForm">
    <input type="file" name="myFile"><br>
    姓名<input type="text" name="name"><br>
    性别<input type="text" name="sex"><br>
    <input type="button" id="btn" value="提交" >
</form>
<img id="headImg">
<script>
    $("#btn").click(function (){
        var formData = new FormData(document.getElementById("userForm"));//获取表单数据
        $.ajax({
            url:"${pageContext.request.contextPath}/upload5",
            type:"post",
            contentType:false,
            processData: false,//设置表单的编码格式为二进制格式,默认true是文本格式
            dataType:"json",
            data:formData,
            success:function (result){
                if (result.code==200){
                    $("#headImg").attr("src",result.imgsrc)
                }
            }
        })
    });
</script>
</body>
</html>

后台代码

package com.aaa.controller;

import com.aaa.entity.User;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: wen_jian_shang_chuan_145
 * @description:
 * @author: zlh
 * @create: 2021-12-07 21:27
 **/
@Controller
public class UploadController05 {
    @RequestMapping("/upload5")
    @ResponseBody
    public Map upload5(MultipartFile myFile, HttpServletRequest request, User user){
        Map map=new HashMap();
        try {
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String endpoint = "oss-cn-beijing.aliyuncs.com";
            // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
            String accessKeyId = "id";
            String accessKeySecret = "密钥";

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream = myFile.getInputStream();
            //获取上传的文件名
            String filename = myFile.getOriginalFilename();
            filename = new Date().getTime() + filename;
            // 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
            ossClient.putObject("zhanglonghui", filename, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();

            String url="https://zhanglonghui."+endpoint+"/"+filename;/*图片回显到前台页面*/
            map.put("code",200);
            map.put("msg","上传成功");
            map.put("imgsrc",url);
            return map;
        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("code",500);
        map.put("msg","上传失败");
        return map;
    }
}

6.多文件上传

同步

前端页面

<%--
  Created by IntelliJ IDEA.
  User: zlh
  Date: 2021/12/7
  Time: 14:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/up02/upload" enctype="multipart/form-data">
    <input type="file" name="myFiles"><br>
    <input type="file" name="myFiles"><br>
    <input type="file" name="myFiles"><br>
    姓名<input type="text" name="name"><br>
    性别<input type="text" name="sex"><br>
    <button>提交</button>
</form>
</body>
</html>

后端页面

package com.aaa.controller;

import com.aaa.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @program: wen_jian_shang_chuan_145
 * @description:
 * @author: zlh
 * @create: 2021-12-07 15:00
 **/
@Controller
@RequestMapping("/up02")
public class UploadController02 {
    @RequestMapping("/upload") //springmvc把上传的文件封装到MultipartFile类中
                                //myfile必须和前台表单中name名一直
    public String upload01(MultipartFile[] myFiles, HttpServletRequest request, User user){
        for (MultipartFile myFile : myFiles) {


            //获取图片在服务器下的路径 getServletContext()获取application对象也就是应用程序对象 获取当前工程对象
            // application属于ServletContext类型
            // getRealPath 获取工程下/upload文件夹的真实路径
            String path = request.getSession().getServletContext().getRealPath("/upload");
            
            //System.out.println(path);
            //2.根据该路径创建文件路径
            File file = new File(path);
            if (!file.exists()) {//file.exists()判断指定path路径文件是否存在
                file.mkdirs();
            }
            //3.获取上传的文件名
            String originalFilename = myFile.getOriginalFilename();
            //System.out.println(originalFilename);
            //4.把上传的文件保存到目标目录
            File target = new File(path + "/" + originalFilename);

            try {
                myFile.transferTo(target);//把上传的文件保存到target目录中
            } catch (Exception e) {
                e.printStackTrace();
            }
            String headImg = "http://localhost:8080/upload/" + originalFilename;
            request.setAttribute("imgsrc", headImg);
            user.setHeadImg(headImg);
            System.out.println(user);

        }return "success";
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值