08,SpringMVC项目上传文件

(1),jar包依赖参考:https://www.toutiao.com/article/7162345189766365699/?log_from=c3a137ae35be9_1667739077005

(2),选择上传文件jsp页面

注意此行不是代码:http://localhost:8085/bl_mave_wf_war_exploded/testExamp/studentListJsp.jsp 这是跳转本页的链接

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>

<%
    String path = request.getContextPath();
    String contextPath = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title></title>
</head>
<body>
    <form action="<%=contextPath %>/studentConter/upFile" method="post" enctype="multipart/form-data">
        请选择要上传的文件:<input type="file" value="请选择" name="upFileName" />
        <input type="submit" value="上传文件" />
    </form>
</body>
<script type="text/javascript">
</script>
</html>

(3),上传文件java代码

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @date: 2022/11/5 23:14
* @desc: 测试控制类
*/
@Controller
@RequestMapping(value = "/studentConter")
public class StudentController {
    @RequestMapping(value = "/upFile")
    public void upFile(HttpServletRequest request
            , HttpServletResponse response
            , @RequestParam(value = "upFileName", required = true)CommonsMultipartFile commonsMultipartFile) {
        if(!commonsMultipartFile.isEmpty()) {
            String fileType = "";
            String upFileName = commonsMultipartFile.getOriginalFilename();
            int dIdx = upFileName.indexOf(".");
            fileType = upFileName.substring(dIdx);
            String fileName = System.currentTimeMillis() + fileType;
            // 项目中的一个文件夹
            String destPath = request.getServletContext().getRealPath("/testExamp/"+ fileName);
            try {
                FileUtils.copyInputStreamToFile(commonsMultipartFile.getInputStream(), new File(destPath));
            } catch (Exception ex1) {
                ex1.printStackTrace();
            }
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值