springmvc 怎么让页面file类型的值 与后台映射

2024-12-15 08:26:18
推荐回答(2个)
回答1:

SpringMVC默认是关闭fileupload功能的,开启该能够并验证文件上传,需要做如下几件事情:
第一:打开SpringMVC的文件上传功能:
***-servlet.xml中配置:
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">




配置后,当SpringMVC接受到multipartRequest的时候,就会把HttpServletRequest转为MultipartHttpServletRequest类型,
第二步:创建上传文件的file.jsp:




一定不要漏掉enctype="multipart/form-data",否则web容器认为这不是一个MultipartRequest请求,会报错org.springframework.web.multipart.MultipartException: The current request is not a multipart request。
第三步:Controller层创建代码:
@RequestMapping(params = {"method=uploadFile"})
public ModelAndView uploadFile(@RequestParam("myfile") MultipartFile myfile,
HttpServletRequest request, HttpServletResponse response) throws Exception {
if(!myfile.isEmpty()){
logger.info(myfile.getName());
byte[] bs= myfile.getBytes() ;
logger.info(new String(bs));
}
return null;
}

部署web应用运行后,能够看到控制台中打印出上传文件的内容,BINGO搞定(SpringMVC依赖common-fileupload.jar,需要加载该jar包)

回答2:

spring mvc 怎么在后台接收到页面上传来的值
index.jsp

<%@ page language="java" contentType="text/html; charset=Utf-8"
pageEncoding="utf-8"%>




Insert title here


欢迎




hello


login








web.xml


xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
springMVC



dispatcher
org.springframework.web.servlet.DispatcherServlet



dispatcher
*.do



index.jsp



dispatcher-servlet.xml


"http://www.springframework.org/dtd/spring-beans.dtd">


class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver">



class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">


helloWorld
login






Hello welcome Login!


sayHello.jsp






Hello Spring World!


sayHello.jsp




HelloWorldAction.java
package com.examp;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;