转载

springboot文件上传等杂项

1,springboot中文件上传

springmvc中配置文件上传写法在boot并不支持

@Bean

public MultipartResolver multipartResolver() {

CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();

multipartResolver.setMaxUploadSize(100000000);

return multipartResolver;

得这样写

@Bean

public MultipartConfigElement multipartConfigElement() {

MultipartConfigFactory factory = new MultipartConfigFactory();

factory.setMaxFileSize("128KB");

factory.setMaxRequestSize("128KB");

return factory.createMultipartConfig();

}

2,拦截器

继承HandlerInterceptorAdapter确实可以拦截,但是afterCompletion在preHandle方法返回false后并

不执行,那么只能在preHandle中处理了,比如转向,ajax请求返回内容

3,关于快速跳转

有时候只是做一个简单的跳转,可以集中写在这里

public void addViewControllers(ViewControllerRegistry registry) {

registry.addViewController("/index").setViewName("/index");

registry.addViewController("/converter").setViewName("/converter");

完整示例:

package com.example.demo.config;

import java.util.List;

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.web.servlet.MultipartConfigFactory;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.InterceptorRegistration;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import org.springframework.web.servlet.view.InternalResourceViewResolver;

import org.springframework.web.servlet.view.JstlView;

//其中默认配置的 /** 映射到 /static (或/public、/resources、/META-INF/resources) 

//其中默认配置的 /webjars/** 映射到 classpath:/META-INF/resources/webjars/ 

/*

spring.mvc.static-path-pattern=

@Configuration

public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/myres/**").addResourceLocations("classpath:/myres/");

//使用外部目录 registry.addResourceHandler("/api_files/**").addResourceLocations("file:D:/data/api_files");

super.addResourceHandlers(registry);

public InternalResourceViewResolver viewResolver() {

InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

viewResolver.setPrefix("/WEB-INF/views/");

viewResolver.setSuffix(".jsp");

viewResolver.setViewClass(JstlView.class);

return viewResolver;

//拦截器

@Override

public void addInterceptors(InterceptorRegistry registry) {// 2

InterceptorRegistration i=registry.addInterceptor(demoInterceptor());

i.addPathPatterns("/jsp/*");//只拦截 /jsp/* 的action

// 1  配置拦截器

public DemoInterceptor demoInterceptor() {

return new DemoInterceptor();

//快速转向

@Override

public void addViewControllers(ViewControllerRegistry registry) {

//registry.addViewController("/index").setViewName("/index");

registry.addViewController("/toUpload").setViewName("/upload");

registry.addViewController("/converter").setViewName("/converter");

registry.addViewController("/sse").setViewName("/sse");

registry.addViewController("/async").setViewName("/async");

@Bean

public MultipartConfigElement multipartConfigElement() {

MultipartConfigFactory factory = new MultipartConfigFactory();

factory.setMaxFileSize("128KB");

factory.setMaxRequestSize("128KB");

return factory.createMultipartConfig();

}

拦截器类

public class DemoInterceptor extends HandlerInterceptorAdapter {// 1

@Override

public boolean preHandle(HttpServletRequest request, // 2

HttpServletResponse response, Object handler) throws Exception {

long startTime = System.currentTimeMillis();

System.out.println("本次始请求处理时间为:" + startTime + "ms");

request.setAttribute("startTime", startTime);

if (request.getHeader("x-requested-with") != null

&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {

response.setHeader("sessionstatus", "timeout"); // 响应头设置session状态

} else {

response.sendRedirect("/");

return false;

@Override

public void postHandle(HttpServletRequest request, // 3

HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

long startTime = (Long) request.getAttribute("startTime");

request.removeAttribute("startTime");

long endTime = System.currentTimeMillis();

System.out.println("本次请求处理时间�?:" + new Long(endTime - startTime) + "ms");

request.setAttribute("handlingTime", endTime - startTime);

}

文件上传页面upload.jsp

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

pageEncoding="UTF-8"%>

<!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>upload page</title>

</head>

<body>

<div class="upload">

<form action="upload" enctype="multipart/form-data" method="post">

<input type="file" name="file"/><br/>

<input type="submit" value="上传">

</form>

</div>

</body>

</html>

文件上传控制器类

@Controller

public class UploadController {

@RequestMapping(value = "/upload",method = RequestMethod.POST)

//MultipartFile[] ,涓婁紶澶氫釜鏂囦欢

public @ResponseBody String upload(@RequestParam("file") MultipartFile file) {//1

FileUtils.writeByteArrayToFile(new File("e:/upload/"+file.getOriginalFilename()),

file.getBytes()); //2

return "ok";

} catch (IOException e) {

e.printStackTrace();

return "wrong";

}

原文  http://www.blogjava.net/fool/archive/2017/09/18/432826.html
正文到此结束
Loading...