java中文件上传

2025-10-20 21:38:23

1、引入maven依赖;

<dependency>

    <groupId>commons-io</groupId>

    <artifactId>commons-io</artifactId>

    <version>2.4</version>

</dependency>

<dependency>  

            <groupId>commons-fileupload</groupId>  

            <artifactId>commons-fileupload</artifactId>  

            <version>1.3.1</version>  

        </dependency>

将此段依赖写入pom.xml文件中

java中文件上传

2、@RequestMapping(value = "index.do",method=RequestMethod.GET)

public String uploadIndex(){

return "upload/index";

}

上传文件首页的后台

java中文件上传

3、<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

    <head>

        <title>图片上传</title>     

    </head>

    <body>

       <form action="index.do" enctype="multipart/form-data" method="post">

        文件上传:<input type="file" name="file" value="请选择文件上传">

        <br>

        <input type="submit" value="提交"><input type="reset" value="重置">

       </form>

    </body>

</html>

上传文件的前端页面

java中文件上传

1、@RequestMapping(value = "index.do",method = RequestMethod.POST)

public String upload(HttpServletRequest request,MultipartFile file,Model model){

String fileName = file.getOriginalFilename();

String path = "E:/image/";

System.out.println(path);

File dest = new File(path+fileName);

java中文件上传

2、try {

file.transferTo(dest);

model.addAttribute("success", true);

model.addAttribute("imageName", fileName);

model.addAttribute("message","文件上传成功");

} catch (IllegalStateException | IOException e) {

// TODO Auto-generated catch block

model.addAttribute("success", false);

model.addAttribute("message","文件上传失败");

e.printStackTrace();

}

return "upload/uploadSuccess";

}

上传文件,将文件写入到对应的文件夹,

java中文件上传

3、<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

    <head>

        <title>图片上传</title>     

    </head>

    <body>

       ${message }

       <img alt="" src="/uploadImage/${imageName }">

    </body>

</htm

对应的上传成功的前端页面

java中文件上传

4、tomcat的server.xml配置

<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>

<!-- 配置虚拟路径 -->

<Context path="/uploadImage" docBase="E:\image\"  reloadable="true"></Context>

      </Host>

路径不能错;

java中文件上传

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢