在spring mvc中上传多部分文件,受弹簧安全保护

时间:2016-07-11 18:42:29

标签: spring spring-security multipart

I am trying to upload the MultiPart file in spring mvc rest services with the application secured with spring security.
The problem is I am able to upload the file succesfully but the uploaded file is corrupted(Not able to open that file),This happens only If I secured the application with spring security.

Here is the web.xml
  

      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd“>

  <!-- The definition of the Root Spring Container shared by all Servlets 
      and Filters -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                  /WEB-INF/spring/appServlet/servlet-context.xml 
                  /WEB-INF/spring/appServlet/security-config.xml
                  /WEB-INF/spring/appServlet/mail-config.xml
      </param-value>
  </context-param>

  <!-- Creates the Spring Container shared by all Servlets and Filters -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- Processes application requests -->
  <servlet>
      <servlet-name>appServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- Spring Security filter <filter> <filter-name>springSecurityFilterChain</filter-name> 
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>

      </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> 
      <url-pattern>/*</url-pattern> </filter-mapping> -->


  <filter>
      <filter-name>MultipartFilter</filter-name>
      <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
  </filter>
  <filter>
      <filter-name>springSecurityFilterChain</filter-name>
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>MultipartFilter</filter-name>
      <servlet-name>/*</servlet-name>
  </filter-mapping>
  <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
      <dispatcher>ERROR</dispatcher>
      <dispatcher>FORWARD</dispatcher>
      <dispatcher>REQUEST</dispatcher>
  </filter-mapping>

  </web-app>
Below is the code on the server side to accept the file
  

package com.upload.controller;   这是我在spring mvc控制器中使用的示例代码,用于将文件上传到服务器,现在我在本地主机中使用

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
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.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

//import com.journaldev.spring.controller.FileUploadController;

@RestController
@RequestMapping("/upload")
// @MultipartConfig(maxFileSize=5242880,maxRequestSize=20971520,location="/home/java-root/Desktop/temp",fileSizeThreshold=0)
public class FileUploadController {
  private static final Logger logger = LoggerFactory
          .getLogger(FileUploadController.class);

  // private static String UPLOAD_LOCATION = "/home/java-root/Desktop/temp/";

  @RequestMapping(value = "/data", method = RequestMethod.POST)
  public @ResponseBody
  String multiFileUpload(@RequestParam("files") MultipartFile file,
          HttpServletRequest request) throws IOException {
      List<MultipartFile> files = Arrays.asList(file);

      List<String> fileNames = new ArrayList<String>();
      String UPLOAD_LOCATION = "/home/java-root/Desktop/temp/";

      if (null != files && files.size() > 0) {
          for (MultipartFile multipartFile : files) {

              String fileName = multipartFile.getOriginalFilename();
              Files.copy(
                      multipartFile.getInputStream(),
                      Paths.get(UPLOAD_LOCATION,
                              multipartFile.getOriginalFilename()));
              // Files.co
              fileNames.add(fileName);
              // Handle file content - multipartFile.getInputStream()

          }
      }
      return "successfull";
  }
}

2 个答案:

答案 0 :(得分:0)

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
        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-4.0.xsd">

    <global-method-security secured-annotations="enabled" />

    <authentication-manager alias="authenticationManager">
        <authentication-provider ref="restAuthenticationProvider" />
    </authentication-manager>

    <http security="none" pattern="/api/webhook" />
    <http security="none" pattern="/api/productsearch" />
    <http auto-config="false" entry-point-ref="restAuthenticationEntryPoint"
        create-session="stateless" authentication-manager-ref="authenticationManager"
        use-expressions="true">
        <intercept-url pattern="/api/customers/guests" access="permitAll" />
        <intercept-url pattern="/api/customers/feedback" access="permitAll" />
        <intercept-url pattern="/api/customers/*" access="isAuthenticated()" />
        <intercept-url pattern="/**" access="permitAll" />
        <custom-filter ref="restSecurityFilter" position="FORM_LOGIN_FILTER" />
        <csrf disabled="true" />
    </http>

    <beans:bean id="restSecurityFilter"
        class="com.condivision.rentongo.security.RestSecurityFilter">
        <beans:constructor-arg name="authenticationManager"
            ref="authenticationManager" />
    </beans:bean>

</beans:beans>

答案 1 :(得分:-1)

2016-07-12 11:47:47 DEBUG FilterSecurityInterceptor:242 - 授权成功 2016-07-12 11:47:47 DEBUG FilterSecurityInterceptor:255 - RunAsManager没有更改Authentication对象 2016-07-12 11:47:47 DEBUG FilterChainProxy:309 - / api / upload / data到达附加过滤链的末尾;继续与原始链 2016-07-12 11:47:47 DEBUG DispatcherServlet:861 - 名为'appServlet'的DispatcherServlet处理[/ rentongo / api / upload / data]的POST请求 2016-07-12 11:47:47 DEBUG CommonsMultipartResolver:259 - 找到大小为73127字节的多部分文件[文件],原始文件名为[push20not.png],存储在[/ home / java-root / Desktop / apache-tomcat- 7.0.67 /工作/卡塔利娜/本地主机/ rentongo / upload_71d6394a_142f_4765_8930_d7dc9c612c8d_00000000.tmp] 2016-07-12 11:47:47 DEBUG RequestMappingHandlerMapping:294 - 查找路径/上传/数据的处理程序方法 2016-07-12 11:47:47 DEBUG RequestMappingHandlerMapping:299 - 返回处理程序方法[public java.lang.String com.condivision.rentongo.controller.FileUploadController.multiFileUpload(org.springframework.web.multipart.MultipartFile,javax.servlet) .http.HttpServletRequest)抛出java.io.IOException] 2016-07-12 11:47:47 DEBUG DefaultListableBeanFactory:248 - 返回单例bean'fileUploadController'的缓存实例 2016-07-12 11:47:47 DEBUG RequestResponseBodyMethodProcessor:163 - 使用[org.springframework.http.converter.StringHttpMessageConverter@574040c1]将[successfull]写成“text / plain; charset = ISO-8859-1” 2016-07-12 11:47:47 DEBUG DispatcherServlet:1034 - Null ModelAndView返回DispatcherServlet,名称为'appServlet':假设HandlerAdapter完成请求处理 2016-07-12 11:47:47 DEBUG CommonsMultipartResolver:282 - 使用原始文件名[push20not.png]清理多部分文件[files],存储在[/home/java-root/Desktop/apache-tomcat-7.0.67 /work/Catalina/localhost/rentongo/upload_71d6394a_142f_4765_8930_d7dc9c612c8d_00000000.tmp] 2016-07-12 11:47:47 DEBUG DispatcherServlet:996 - 成功完成请求 2016-07-12 11:47:47 DEBUG ExceptionTranslationFilter:116 - 链处理正常 2016-07-12 11:47:47 DEBUG SecurityContextPersistenceFilter:105 - SecurityContextHolder现已清除,请求处理完成