springMvc实现文件上传

1、简介

  • 实现文件上传
    • 提交请求必须post
    • enctype必须配置成:multipart/form-data
    • springmvc它是依赖于apache Fileupload的库实现

2、如何在springmvc实现文件上传

  • 提供MultipartFile对象实现文件上传
  • MultipartFile对象中的常用方法如下:
    • byte[] getBytes():获取文件数据
    • String getContentType[]:获取文件MIME类型,如image/jpeg等
    • InputStream getInputStream():获取文件流
    • String getName():获取表单中文件组件的名字
    • String getOriginalFilename():获取上传文件的原名
    • Long getSize():获取文件的字节大小,单位为byte
    • boolean isEmpty():是否有上传文件
    • void transferTo(File dest):将上传文件保存到一个目录文件中
  • 库的使用

在这里插入图片描述

  • handle
package com.cn.home;

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

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author Lin_Home
 * @Date 2020/10/21 14:48
 * @Version 1.0
 */
@Controller
public class ControllerDemo {
    //访问到jsp 文件
    @RequestMapping("/form")
    public String ToFrom() {
        return "FileFrom";
    }


    @RequestMapping("/upload")
    public String upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) {
        System.out.println("获取上传文件原名 = " + file.getOriginalFilename());
        //上传文件的绝对路径
        String uploadfilePath = httpServletRequest.getServletContext().getRealPath("/upload");
        System.out.println("上传文件的绝对路径 = " + uploadfilePath);
        //获取到是文件名字
        String uploadFileName = file.getOriginalFilename();

        //生成随机的前置名
        String uuid= UUID.randomUUID().toString().replace("-", "");

        //创建一个File对象
        String suffix=uploadFileName.substring(uploadFileName.lastIndexOf("."));

        File uploadFile = new File(uploadfilePath, uuid+suffix);


        if (!uploadFile.exists()) {
            //创建文件
            uploadFile.mkdirs();
            try {
                //将上传文件内容复制到目标文件
                file.transferTo(uploadFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "hello";
    }
}

  • jsp 页面
<%--
  Created by IntelliJ IDEA.
  User: Lin_Home
  Date: 2020/10/21
  Time: 14:50
  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
        action="${pageContext.servletContext.contextPath}/upload" method="post" enctype="multipart/form-data">
        文件:<input type="file" name="file"/><br/>
    <input type="submit" value="上传"/>
</form>
</body>
</html>
  • 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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:component-scan base-package="com.cn.home"/>

    <!--
    1、注解映射器及适配器的实现
    2、消息转换器的配置实现(默认jackjson)
    3、数据转换
    4、数据格式化处理
    -->
    <mvc:annotation-driven />
    <!--允许直接访问静态资源(js/html/img/css)-->
    <mvc:default-servlet-handler />

    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传文件大小上限,单位为字节(10MB) -->
        <property name="maxUploadSize">
            <value>10485760</value>
        </property>
        <!-- 请求的编码格式,必须和jSP的pageEncoding属性一
        致,以便正确读取表单的内容,默认为ISO-8859-1 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>


    <!-- 视图解析器  -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <!-- 后缀 -->
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值