`
lobin
  • 浏览: 425546 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

关于Spring Boot中CommonsMultipartFile&StandardMultipartFile兼容问题

 
阅读更多

Spring Boot默认使用StandardServletMultipartResolver处理Multipart。

 

对应的使用StandardMultipartFile来接收文件数据。

 

	private static class StandardMultipartFile implements MultipartFile, Serializable {

		private final Part part;

		private final String filename;

		public StandardMultipartFile(Part part, String filename) {
			this.part = part;
			this.filename = filename;
		}

		@Override
		public String getName() {
			return this.part.getName();
		}

		@Override
		public String getOriginalFilename() {
			return this.filename;
		}

		@Override
		public String getContentType() {
			return this.part.getContentType();
		}

		@Override
		public boolean isEmpty() {
			return (this.part.getSize() == 0);
		}

		@Override
		public long getSize() {
			return this.part.getSize();
		}

		@Override
		public byte[] getBytes() throws IOException {
			return FileCopyUtils.copyToByteArray(this.part.getInputStream());
		}

		@Override
		public InputStream getInputStream() throws IOException {
			return this.part.getInputStream();
		}

		@Override
		public void transferTo(File dest) throws IOException, IllegalStateException {
			this.part.write(dest.getPath());
			if (dest.isAbsolute() && !dest.exists()) {
				// Servlet 3.0 Part.write is not guaranteed to support absolute file paths:
				// may translate the given path to a relative location within a temp dir
				// (e.g. on Jetty whereas Tomcat and Undertow detect absolute paths).
				// At least we offloaded the file from memory storage; it'll get deleted
				// from the temp dir eventually in any case. And for our user's purposes,
				// we can manually copy it to the requested location as a fallback.
				FileCopyUtils.copy(this.part.getInputStream(), new FileOutputStream(dest));
			}
		}
	}

 

 

 

MultipartFile

CommonsMultipartFile

StandardMultipartFile

 

MultipartResolver

 

StandardServletMultipartResolver

CommonsMultipartResolver

 

如果希望用CommonsMultipartFile来接收文件数据

 

在没有配置multipartResolver为CommonsMultipartResolver,使用CommonsMultipartResolver来处理Multipart,这种情况下,报如下错误:

 

Failed to convert request element: org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile': no matching editors or conversion strategy found

 

 

如果multipartResolver配置如下:

 

@Bean(name = "multipartResolver")
public CommonsMultipartResolver getCommonsMultipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(20971520);
    multipartResolver.setMaxInMemorySize(1048576);
    return multipartResolver;
}

使用CommonsMultipartResolver来处理Multipart,通过CommonsMultipartFile无法接收到文件。

 

需要关闭Spring Boot的Multipart自动配置

 

@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})

 

 

如果希望用StandardMultipartFile来接收文件数据

 

org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.StandardMultipartFile#filename

这里获取的文件名如果是中文的话,总是乱码。

 

/*
 * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/FilePart.java,v 1.19 2004/04/18 23:51:37 jsdever Exp $
 * $Revision: 480424 $
 * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
 *
 * ====================================================================
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package org.apache.commons.httpclient.methods.multipart;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This class implements a part of a Multipart post object that
 * consists of a file.
 *
 * @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
 * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
 * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
 * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
 * @author <a href="mailto:mdiggory@latte.harvard.edu">Mark Diggory</a>
 * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
 * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
 *
 * @since 2.0
 *
 */
public class MultipartFilePart extends PartBase {

    /** Default content encoding of file attachments. */
    public static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";

    /** Default charset of file attachments. */
    public static final String DEFAULT_CHARSET = "ISO-8859-1";

    /** Default transfer encoding of file attachments. */
    public static final String DEFAULT_TRANSFER_ENCODING = "binary";

    /** Log object for this class. */
    private static final Log LOG = LogFactory.getLog(MultipartFilePart.class);

    /** Attachment's file name */
    protected static final String FILE_NAME = "; filename=";

    /** Attachment's file name as a byte array */
    private static final byte[] FILE_NAME_BYTES =
            EncodingUtil.getAsciiBytes(FILE_NAME);

    /** Source of the file part. */
    private PartSource source;

    /**
     * FilePart Constructor.
     *
     * @param name the name for this part
     * @param partSource the source for this part
     * @param contentType the content type for this part, if <code>null</code> the
     * {@link #DEFAULT_CONTENT_TYPE default} is used
     * @param charset the charset encoding for this part, if <code>null</code> the
     * {@link #DEFAULT_CHARSET default} is used
     */
    public MultipartFilePart(String name, PartSource partSource, String contentType, String charset) {

        super(
                name,
                contentType == null ? DEFAULT_CONTENT_TYPE : contentType,
                charset == null ? "ISO-8859-1" : charset,
                DEFAULT_TRANSFER_ENCODING
        );

        if (partSource == null) {
            throw new IllegalArgumentException("Source may not be null");
        }
        this.source = partSource;
    }

    /**
     * FilePart Constructor.
     *
     * @param name the name for this part
     * @param partSource the source for this part
     */
    public MultipartFilePart(String name, PartSource partSource) {
        this(name, partSource, null, null);
    }

    /**
     * FilePart Constructor.
     *
     * @param name the name of the file part
     * @param file the file to post
     *
     * @throws FileNotFoundException if the <i>file</i> is not a normal
     * file or if it is not readable.
     */
    public MultipartFilePart(String name, File file)
            throws FileNotFoundException {
        this(name, new FilePartSource(file), null, null);
    }

    /**
     * FilePart Constructor.
     *
     * @param name the name of the file part
     * @param file the file to post
     * @param contentType the content type for this part, if <code>null</code> the
     * {@link #DEFAULT_CONTENT_TYPE default} is used
     * @param charset the charset encoding for this part, if <code>null</code> the
     * {@link #DEFAULT_CHARSET default} is used
     *
     * @throws FileNotFoundException if the <i>file</i> is not a normal
     * file or if it is not readable.
     */
    public MultipartFilePart(String name, File file, String contentType, String charset)
            throws FileNotFoundException {
        this(name, new FilePartSource(file), contentType, charset);
    }

    /**
     * FilePart Constructor.
     *
     * @param name the name of the file part
     * @param fileName the file name
     * @param file the file to post
     *
     * @throws FileNotFoundException if the <i>file</i> is not a normal
     * file or if it is not readable.
     */
    public MultipartFilePart(String name, String fileName, File file)
            throws FileNotFoundException {
        this(name, new FilePartSource(fileName, file), null, null);
    }

    /**
     * FilePart Constructor.
     *
     * @param name the name of the file part
     * @param fileName the file name
     * @param file the file to post
     * @param contentType the content type for this part, if <code>null</code> the
     * {@link #DEFAULT_CONTENT_TYPE default} is used
     * @param charset the charset encoding for this part, if <code>null</code> the
     * {@link #DEFAULT_CHARSET default} is used
     *
     * @throws FileNotFoundException if the <i>file</i> is not a normal
     * file or if it is not readable.
     */
    public MultipartFilePart(String name, String fileName, File file, String contentType, String charset)
            throws FileNotFoundException {
        this(name, new FilePartSource(fileName, file), contentType, charset);
    }

    /**
     * Write the disposition header to the output stream
     * @param out The output stream
     * @throws IOException If an IO problem occurs
     * @see Part#sendDispositionHeader(OutputStream)
     */
    protected void sendDispositionHeader(OutputStream out)
            throws IOException {
        LOG.trace("enter sendDispositionHeader(OutputStream out)");
        super.sendDispositionHeader(out);
        String filename = this.source.getFileName();
        if (filename != null) {
            out.write(FILE_NAME_BYTES);
            out.write(QUOTE_BYTES);
            out.write(EncodingUtil.getBytes(filename, getCharSet()));
            out.write(QUOTE_BYTES);
        }
    }

    /**
     * Write the data in "source" to the specified stream.
     * @param out The output stream.
     * @throws IOException if an IO problem occurs.
     * @see org.apache.commons.httpclient.methods.multipart.Part#sendData(OutputStream)
     */
    protected void sendData(OutputStream out) throws IOException {
        LOG.trace("enter sendData(OutputStream out)");
        if (lengthOfData() == 0) {

            // this file contains no data, so there is nothing to send.
            // we don't want to create a zero length buffer as this will
            // cause an infinite loop when reading.
            LOG.debug("No data to send.");
            return;
        }

        byte[] tmp = new byte[4096];
        InputStream instream = source.createInputStream();
        try {
            int len;
            while ((len = instream.read(tmp)) >= 0) {
                out.write(tmp, 0, len);
            }
        } finally {
            // we're done with the stream, close it
            instream.close();
        }
    }

    /**
     * Returns the source of the file part.
     *
     * @return The source.
     */
    protected PartSource getSource() {
        LOG.trace("enter getSource()");
        return this.source;
    }

    /**
     * Return the length of the data.
     * @return The length.
     * @throws IOException if an IO problem occurs
     * @see org.apache.commons.httpclient.methods.multipart.Part#lengthOfData()
     */
    protected long lengthOfData() throws IOException {
        LOG.trace("enter lengthOfData()");
        return source.getLength();
    }

}

 

 

客户端上传代码:

 

    @Test
    public void test() {
        String localFile = "E:\\docs\\装饰模式.bmp";
        File file = new File(localFile);
//        String url = "http://localhost:8081/upload";
        String url = "http://localhost:8081/upload?version=1.1";
        PostMethod filePost = new PostMethod(url){//这个用来中文乱码
            public String getRequestCharSet() {
                return "UTF-8";//
            }
        };
//        filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        HttpClient client = new HttpClient();
//        filePost.setRequestHeader();
        try {
            String secret = UUID.randomUUID().toString();
            System.out.println("secret:" + secret);
            filePost.setParameter("secret", secret);
            filePost.setParameter("secret", secret);
            Part[] parts = {
                    new StringPart("newSecret", secret),
                    new StringPart("fileName", "ABC" + file.getName(), "UTF-8"),
                    // "application/octet-stream; charset=ISO-8859-1", "ISO-8859-1"
                    new FilePart("file",
                            file, null, "utf-8") {
                        protected void sendDispositionHeader(OutputStream out) throws IOException {
                            super.sendDispositionHeader(out);
                            String filename = getSource().getFileName();
                            if (filename != null) {
                                out.write(EncodingUtil.getAsciiBytes(FILE_NAME));
                                out.write(QUOTE_BYTES);
//                                out.write(EncodingUtil.getBytes(filename, "utf-8"));
                                out.write(EncodingUtil.getBytes(filename, getCharSet()));
                                out.write(QUOTE_BYTES);
                            }
                        }
                    },
//                    new FilePart(new String(file.getName().getBytes("ISO-8859-1"), "UTF-8"), file)
            };
            filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

            int status = client.executeMethod(filePost);
            if (status == HttpStatus.SC_OK) {
                System.out.println("SUCCESS");
            } else {
                System.out.println("FAIL: status: " + status);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            filePost.releaseConnection();
        }
    }

 

 

 

 

0
0
分享到:
评论

相关推荐

    Spring Cloud+Spring Boot+Git&GitHub;+Spring in action+SpringBoot

    6. **Spring Boot实战**: 这两本关于Spring Boot实战的PDF书籍,由丁雪丰翻译的版本和清晰版,为读者提供了实际操作的指导,包括Spring Boot的基础用法、开发环境配置、测试、部署等方面,是学习和掌握Spring Boot的...

    基于Spring Boot 3.0、 Spring Cloud 2022 & Alibaba 的微服务RBAC 权限管理系统

    介绍一个基于Spring Boot 3.0、Spring Cloud 2022 & Alibaba的微服务RBAC权限管理系统。该系统可以实现微服务RBAC权限管理,通过RBAC权限管理机制对用户访问系统的权限进行限制,从而提高系统的安全性和可用性。同时...

    spring-boot中文教程

    描述:Spring Boot中文文档是Spring Boot官方文档的中文翻译版,它包含了Spring Boot的基本介绍、快速入门、核心特性、高级特性等内容,可以帮助用户快速了解和掌握Spring Boot的使用方法和技巧。 Spring Boot是一款...

    learning spring boot 2.0

    第二版的发布表明作者在原有基础上增加了更多关于Spring Boot 2.0的新特性介绍和使用指导。 描述中提到本书是英文高清版,2017年11月出版,属于第二版。由于本书的出版时间相对较新,因此其中关于Spring Boot的知识...

    spring boot资料以及项目

    在资料中,你可能会找到关于Spring Boot的官方文档、教程、博客文章和视频课程。这些内容会详细介绍如何创建Spring Boot项目、如何配置Spring Boot、如何使用Spring Initializr初始化项目、以及如何使用Maven或...

    LEARNING SPRING BOOT 3.0 - THIRD EDITION

    Spring Boot是Spring生态系统中的一个核心组件,它通过自动化配置、起步依赖和内嵌式Web服务器等功能,极大地简化了Java应用的开发。 在Spring Boot 3.0版本中,我们可以期待一系列更新和改进,包括性能提升、新...

    最新Spring Boot Admin 官方参考指南-中文版-2.x

    Spring Boot Admin 是...通过其直观的UI和与Spring Boot Actuator的紧密集成,开发者可以轻松地获取应用程序的实时状态,进行问题排查和性能优化。无论是快速部署还是深度定制,Spring Boot Admin都能提供有力的支持。

    spring boot 中文文档

    Spring Boot是Spring社区提供的一个全新项目,旨在简化Spring应用的初始搭建以及开发过程。它使用特定的方式配置应用程序,这样就可以避免大量的模板配置。Spring Boot专注于快速和广泛的应用程序开发,它遵循“约定...

    Spring Boot整合Spring Batch,实现批处理

    在Java开发领域,Spring Boot和Spring Batch的整合是构建高效...通过学习和实践这个示例,你不仅可以掌握如何在Spring Boot中使用Spring Batch,还能了解批处理的最佳实践,这对于处理大数据量的应用场景非常有价值。

    JDK 8 + Spring Boot 2.7.18

    【标题】"JDK 8 + Spring Boot 2.7.18" 指的是一个基于Java 8和Spring Boot 2.7.18版本的开发环境或项目。这个组合是现代Java应用程序开发中的常见选择,因为它提供了高效能、易用性和强大的功能。 【JDK 8】是Java...

    Spring Boot讲义.pdf

    在Spring Boot中,"快速入门"通常指的是新手或初学者对Spring Boot的基本认识和基础使用,能够快速构建和部署一个Spring Boot应用程序。 ### Spring Boot概述 #### 1.1. 什么是Spring Boot Spring Boot是Spring...

    Spring Boot 进阶笔记(详细全面) 中文PDF完整版.pdf

    1. **自动配置**:Spring Boot 根据项目中包含的依赖自动生成相应的配置,例如,引入 `spring-boot-starter-web` 会自动配置 Spring MVC 和 Tomcat 服务器。 2. **起步依赖(Starter POMs)**:Spring Boot 提供了一...

    Spring Boot 2.5.0简单学习pdf资料

    在 Spring Boot 2.5.0 中,项目开发流程通常包括需求分析、概要设计、详细设计、编码、测试和部署等几个阶段。在每个阶段都需要遵守一定的流程和规范,以确保项目的质量和可维护性。 环境搭建 在 Spring Boot ...

    《Vue Spring Boot前后端分离开发实战》源码Vue+Spring Boot前后端分离开发实战教学课件(PPT)

    在现代Web应用开发中,Vue.js和Spring Boot的结合已经成为了一种常见的前后端分离架构模式。这本《Vue Spring Boot前后端分离开发实战》的源码提供了深入学习和实践这一技术栈的机会。以下是对其中涉及知识点的详细...

    Spring Boot 2 Recipes

    获取Spring Boot 2微框架的可重用代码配方和代码段 了解Spring Boot 2如何与其他Spring API,工具和框架集成 访问Spring MVC和新的Spring Web Sockets,以实现更简单的Web开发 使用微服务进行Web服务开发并与Spring ...

    spring-boot-ssm:springboot-ssm 是一个基于Spring Boot & Spring & Spring MVC & MyBatis的简单通用的项目,用于快速构建中小型API的后端服务系统

    spring-boot-ssm 是一个基于Spring Boot & Spring & Spring MVC & MyBatis的简单通用的项目,用于快速构建中小型API的后端服务系统. 可以做为一个种子项目,进行改造升级. 另外,还有个对应的Vue+ElementUI的前端项目,...

    Spring boot 示例 官方 Demo

    spring-boot-helloWorld:spring-boot的helloWorld版本 spring-boot-mybaits-annotation:注解版本 spring-boot-mybaits-xml:xml配置版本 spring-boot-mybatis-mulidatasource:springboot+mybatis多数据源最简解决...

    Spring Boot 2 Cookbook 第二版

    《Spring Boot 2 Cookbook 第二版》是一本针对Java开发者极具价值的开发指南,它深入浅出地介绍了Spring Boot 2这一强大框架的使用方法。Spring Boot是Spring框架的一个子项目,旨在简化Java应用程序的初始搭建以及...

    Spring Boot中文文档(基于1.4.1翻译)

    - 提供了关于如何在Spring Boot中创建和使用Spring Beans和依赖注入的信息。 - 讨论了使用`@SpringBootApplication`注解的细节,该注解是一个组合注解,包括了`@Configuration`、`@EnableAutoConfiguration`和`@...

    spring-boot中文API文档

    13. **常见问题**:解答在使用Spring Boot过程中可能遇到的问题,以及如何解决。 这份中文API文档不仅对初学者有指导意义,也为经验丰富的开发者提供了详细的参考信息,帮助他们深入理解Spring Boot的内部工作原理...

Global site tag (gtag.js) - Google Analytics