当前位置: 首页 > 知识库问答 >
问题:

在Spring mvc中上传多部分文件,该文件受到Spring Security保护

百里成仁
2023-03-14
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

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

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个答案

阮喜
2023-03-14

2016-07-12 11:47:47调试过滤器安全接口:242-授权成功2016-07-12 11:47:47调试过滤器安全接口:255-RunaManager未更改身份验证对象2016-07-12 11:47:47调试过滤器链Proxy:309-/api/上载/数据到达附加过滤器链的末尾;继续原始链2016-07-12 11:47:47调试DispatcherServlet:861-名为“appServlet”的DispatcherServlet处理[rentongo/api/upload/data]2016-07-12 11:47:47调试CommonsMultipartResolver:259]的POST请求-找到大小为73127字节的多部分文件[files],原始文件名为[push20not.png],存储在[/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调试请求映射handler映射:294-查找路径/上载/数据的处理程序方法2016-07-12 11:47:47调试请求映射: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调试DefaultListableBeanFactory:248-返回单例bean“FileUploadController”的缓存实例2016-07-1211:47:47调试请求响应eBodyMethodProcessor:163-使用[org.springframework.http.converter]将[successfull]写成“text/plain;charset=ISO-8859-1”。StringHttpMessageConverter@574040c1]2016-07-12 11:47:47调试DispatchersServlet:1034-返回给名为“appServlet”的DispatchersServlet的Null ModelAndView:假设HandlerAdapter完成了请求处理2016-07-12 11:47:47调试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调试调度员服务:996-成功完成请求2016-07-12 11:47:47调试异常TranslationFilter:116-链正常处理2016-07-12 11:47:47调试SecurityContextPersistenceFilter:105-请求处理完成后,SecurityContextHolder现在已清除

澹台奇略
2023-03-14
<?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>
 类似资料:
  • 我正在Spring controller中努力实现多部分文件上传。我读过很多问题,谷歌,但似乎什么都不管用。 我明白了 我的BE控制器: FE,angularJS: HTML: 还有应用程序。属性包括: 更新: 当我按照@Byeon0gam的建议从我的控制器中删除@RequestParam时,我不再会遇到这个错误,但是我的文件在控制器中是空的。虽然在FE服务中,如我所见,它不是空的:

  • 我试图创建一个页面,用户可以张贴图像及其细节。现在,当我测试来自postman的spring boot服务时,我能够成功地在服务中获取文件。当我试图从angular5中做同样的事情时,多部分文件在服务中没有被识别,并且总是得到空数组。 我的角服务代码如下 } 我已经尝试添加标头,如multipart/form-data,并将其设置为un定义。无论哪种方式,我都收到了错误。在发布到这里之前,我已经广

  • 我正在尝试使用@Controller和@Request estMap使用Spring 3.1.2上传多个文件。 下面是我做的和我的配置。 格式 : 控制器方法: 我的会议: 提交表单确实会转到添加文件系统映像方法。locId 参数的数据位于此处,但“文件”参数未绑定。无论我尝试过什么参数/字段名称/参数类型的组合,它都是系统性的空值。 HttpServletRequest参数是一个org.spri

  • 我正在使用这个音频记录和视频文件,它是工作的,但我想用OKHTTP取代它。我没弄明白。有人能帮我一下吗?

  • 我已经实现了一个Spring MVC REST服务,它接受一个包含文件上传和JSON主体的多部分消息。以下是所涉及的主要类: 我的问题是servlet初始化器(c:/temp/)中定义的临时位置包含。tmp文件夹,这些文件夹是在每次对该服务的请求之后创建的,并且从未被删除。在记事本中打开它们,看起来它们只包含请求中发送的JSON的纯文本副本,而不包含上传文件的字节。我一辈子都想不出如何让这些文件在

  • 我正在尝试向S3发出上传请求,以便上传一个文件。在我目前掌握的最可靠的代码下面, 我总是从服务器收到400(错误请求)。我不确定我是否正确使用了多部分上传。 但是当我使用像POSTMAN这样的任何Rest客户端做同样的事情时,它工作得很好, 这将是有帮助的,如果有人可以抛出一些光在多部分上传放心。 我已经查看了以下链接, 放心文档 放心的示例 编辑1: 我试着将上面的邮递员请求转换成curl,并用