jsp编码
[html] view plain copy
在CODE上查看代码片派生到我的代码片
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传</title>
</head>
<body>
<h>上传</h>
<form name="userForm" action="/springMVC7/file/upload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file">
<input type="submit" value="提交">
</form>
</body>
</html>
界面上,请注意method的方式,以及enctype
在springMVC的配置文件中添加如下配置
[html] view plain copy
在CODE上查看代码片派生到我的代码片
<!-- 上传文件的配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>
后台代码
[java] view plain copy
在CODE上查看代码片派生到我的代码片
package com.tgb.web.controller.annotation.upload;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.tgb.web.controller.entity.User;
@Controller
@RequestMapping("/file")
public class UploadController {
@RequestMapping(value="/upload")
public String addUser(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException{
System.out.println("fileName--->"+file.getOriginalFilename());
if(!file.isEmpty()){
try {
FileOutputStream os = new FileOutputStream("D:/"+new Date().getTime()+file.getOriginalFilename());
InputStream in = file.getInputStream();
int b=0;
while((b=in.read())!=-1){
os.write(b);
}
os.flush();
os.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "success";
}
@RequestMapping(value="/addUserJson")
public String addUserJson(User user,HttpServletRequest request,HttpServletResponse response){
return "userManager";
}
@RequestMapping(value="/toUser")
public String toUser(){
return "upload";
}
}
SpringMVC文件上传
最新推荐文章于 2023-01-07 00:22:55 发布