001/*
002 * Copyright 2002-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.multipart.support;
018
019import java.io.IOException;
020
021import org.springframework.beans.propertyeditors.ByteArrayPropertyEditor;
022import org.springframework.lang.Nullable;
023import org.springframework.web.multipart.MultipartFile;
024
025/**
026 * Custom {@link java.beans.PropertyEditor} for converting
027 * {@link MultipartFile MultipartFiles} to byte arrays.
028 *
029 * @author Juergen Hoeller
030 * @since 13.10.2003
031 */
032public class ByteArrayMultipartFileEditor extends ByteArrayPropertyEditor {
033
034        @Override
035        public void setValue(@Nullable Object value) {
036                if (value instanceof MultipartFile) {
037                        MultipartFile multipartFile = (MultipartFile) value;
038                        try {
039                                super.setValue(multipartFile.getBytes());
040                        }
041                        catch (IOException ex) {
042                                throw new IllegalArgumentException("Cannot read contents of multipart file", ex);
043                        }
044                }
045                else if (value instanceof byte[]) {
046                        super.setValue(value);
047                }
048                else {
049                        super.setValue(value != null ? value.toString().getBytes() : null);
050                }
051        }
052
053        @Override
054        public String getAsText() {
055                byte[] value = (byte[]) getValue();
056                return (value != null ? new String(value) : "");
057        }
058
059}