广告
返回顶部
首页 > 资讯 > 精选 >如何使用SpringMVC接收文件流上传和表单参数
  • 786
分享到

如何使用SpringMVC接收文件流上传和表单参数

2023-06-29 06:06:58 786人浏览 泡泡鱼
摘要

这篇文章主要介绍“如何使用springMVC接收文件流上传和表单参数”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“如何使用springmvc接收文件流上传和表单参数”文章能帮助大家解决问题。接收文件

这篇文章主要介绍“如何使用springMVC接收文件流上传和表单参数”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“如何使用springmvc接收文件流上传和表单参数”文章能帮助大家解决问题。

接收文件流上传和表单参数

在SpringMVC中,接收文件流非常简单,我们可以写个接口用来接收一些文件,同时还可以接收表单参数。

代码参考如下:

JAVA服务端代码

@RequestMapping(value = "/receive/file", method = POST)public String receiveFile(httpservletRequest request) {    // 转换为 MultipartHttpServletRequest    if (request instanceof MultipartHttpServletRequest) {        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;        // 通过表单中的参数名来接收文件流(可用 file.getInputStream() 来接收输入流)        MultipartFile file = multipartRequest.getFile("file");        System.out.println("上传的文件名称:" + file.getOriginalFilename());        System.out.println("上传的文件大小:" + file.getSize());        // 接收其他表单参数        String name = multipartRequest.getParameter("name");        String content = multipartRequest.getParameter("content");        System.out.println("name:" + name);        System.out.println("content:" + content);        return "OK";    } else {        return "不是 MultipartHttpServletRequest";    }}

html页面代码

<fORM action="http://127.0.0.1:8080/receive/file" method="post" enctype="multipart/form-data">    <input type="file" name="file" id="file">    <input type="text" name="content" value="内容">    <input type="text" name="name" value="名称">    <button type="submit">提交请求</button></form>

SpringMVC接收文件上传,并对文件做处理

  • http client版本4.1.1

  • spring版本3.2.11

在这个例子里面我接收了文件,并转发给另一个机器,其实接收的时候文件的流已经拿到了,想保存到本地,或者对文件分析,自己可以斟酌。

springmvc配置

<?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        http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd">    <context:component-scan base-package="com"/>    <!-- if you use annotation you must configure following setting -->    <mvc:annotation-driven/>    <bean class="org.springframework.WEB.servlet.mvc.support.ControllerClassNameHandlerMapping"/>    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>    <!-- 处理JSON -->    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">        <property name="supportedMediaTypes">            <list>                <value>text/html;charset=UTF-8</value>            </list>        </property>    </bean>    <mvc:default-servlet-handler/>    <!-- 日志输出拦截器 -->    <mvc:interceptors>        <bean class="com.steward.interceptor.AccessInteceptor">            <property name="accessLog">                <value>true</value>            </property>        </bean>    </mvc:interceptors>    <!-- 解析器 -->    <bean class="org.springframework.web.servlet.view.ContentNeGotiatingViewResolver">        <property name="mediaTypes">            <map>                <entry key="html" value="text/html"/>                <entry key="json" value="application/json"/>            </map>        </property>        <property name="viewResolvers">            <list>                <ref bean="viewResolver"/>            </list>        </property>        <property name="defaultViews">            <list>                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>            </list>        </property>    </bean>    <!-- 异常处理 -->    <bean id="exceptionHandler" class="com.steward.exception.ExceptionHandler"/>    <!-- 文件上传 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>    <!-- 配置freeMarker的模板路径 -->    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property>        <property name="suffix" value=".html"></property>        <property name="contentType" value="text/html;charset=UTF-8"/>        <property name="requestContextAttribute" value="rc"></property>    </bean>    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">        <property name="templateLoaderPath" value="/WEB-INF/templates/"></property>        <property name="freemarkerSettings">            <props>                <prop key="template_update_delay">0</prop>                <prop key="default_encoding">UTF-8</prop>                <prop key="locale">zh_CN</prop>                <prop key="number_format">0.##########</prop>                <prop key="template_exception_handler">ignore</prop>            </props>        </property>        <property name="freemarkerVariables">            <map>                <entry key="getVersion" value-ref="getVersion"/>            </map>        </property>    </bean>    <bean id="getVersion" class="com.steward.freemarker.GetVersion"/></beans>

controller代码如下

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)@ResponseBodypublic String uploadFile(HttpServletRequest request) throws Exception {    FileOutputStream fos = null;    InputStream in = null;    String fileUrl = null;    try {        //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());        //检查form中是否有enctype="multipart/form-data"        if (multipartResolver.isMultipart(request)) {            //将request变成多部分request            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;            //获取multiRequest 中所有的文件名            Iterator iterator = multiRequest.getFileNames();            while (iterator.hasNext()) {                MultipartFile multipartFile = multiRequest.getFile(iterator.next().toString());                in = multipartFile.getInputStream();                File file = new File(multipartFile.getOriginalFilename());                fos = new FileOutputStream(file);                byte[] buff = new byte[1024];                int len = 0;                while ((len = in.read(buff)) > 0) {                    fos.write(buff, 0, len);                }                String uploadUrl = platformHttpsDomain + "/uploadFile";                HttpPost post = new HttpPost(uploadUrl);                HttpClient httpclient = new DefaultHttpClient();                MultipartEntity reqEntity = new MultipartEntity();                reqEntity.addPart("file", new FileBody(file));                post.setEntity(reqEntity);                HttpResponse response = httpclient.execute(post);                int statusCode = response.getStatusLine().getStatusCode();                if (statusCode == HttpStatus.SC_OK) {                    fileUrl = EntityUtils.toString(response.getEntity());                }                file.deleteOnExit();            }        }    } catch (Exception e) {        e.printStackTrace();    } finally {        if (fos != null) {            try {                fos.close();            } catch (IOException e) {            }        }        if (in != null) {            try {                in.close();            } catch (IOException e) {            }        }    }    return fileUrl;}

关于“如何使用SpringMVC接收文件流上传和表单参数”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网精选频道,小编每天都会为大家更新不同的知识点。

--结束END--

本文标题: 如何使用SpringMVC接收文件流上传和表单参数

本文链接: https://www.lsjlt.com/news/323204.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 使用SpringMVC接收文件流上传和表单参数
    目录接收文件流上传和表单参数JAVA服务端代码HTML页面代码SpringMVC接收文件上传,并对文件做处理springmvc配置controller代码如下接收文件流上传和表单参数...
    99+
    2022-11-13
  • 如何使用SpringMVC接收文件流上传和表单参数
    这篇文章主要介绍“如何使用SpringMVC接收文件流上传和表单参数”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“如何使用SpringMVC接收文件流上传和表单参数”文章能帮助大家解决问题。接收文件...
    99+
    2023-06-29
  • 在SpringMVC中使用bean如何实现接收form表单提交的参数
    今天就跟大家聊聊有关在SpringMVC中使用bean如何实现接收form表单提交的参数,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。使用bean来接收form表单提交的参数时,po...
    99+
    2023-05-31
    springmvc form bean
  • 如何使用Ajax进行文件与其他参数的上传功能
    这篇文章主要为大家展示了“如何使用Ajax进行文件与其他参数的上传功能”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何使用Ajax进行文件与其他参数的上传功能...
    99+
    2022-10-19
  • 如何使用MySQL和Java实现一个简单的文件上传功能
    要使用MySQL和Java实现一个简单的文件上传功能,可以按照以下步骤进行:1. 创建一个MySQL数据库表来存储上传的文件信息。表...
    99+
    2023-10-20
    MySQL
  • CentOS中如何使用Shell脚本实现每天自动备份网站文件和数据库并上传到FTP中
    这篇文章主要讲解了“CentOS中如何使用Shell脚本实现每天自动备份网站文件和数据库并上传到FTP中”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“CentOS中如何使用Shell脚本实现...
    99+
    2023-06-09
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作