001/* 002 * Copyright 2002-2008 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.web.multipart.MultipartFile; 023 024/** 025 * Custom {@link java.beans.PropertyEditor} for converting 026 * {@link MultipartFile MultipartFiles} to byte arrays. 027 * 028 * @author Juergen Hoeller 029 * @since 13.10.2003 030 */ 031public class ByteArrayMultipartFileEditor extends ByteArrayPropertyEditor { 032 033 @Override 034 public void setValue(Object value) { 035 if (value instanceof MultipartFile) { 036 MultipartFile multipartFile = (MultipartFile) value; 037 try { 038 super.setValue(multipartFile.getBytes()); 039 } 040 catch (IOException ex) { 041 throw new IllegalArgumentException("Cannot read contents of multipart file", ex); 042 } 043 } 044 else if (value instanceof byte[]) { 045 super.setValue(value); 046 } 047 else { 048 super.setValue(value != null ? value.toString().getBytes() : null); 049 } 050 } 051 052 @Override 053 public String getAsText() { 054 byte[] value = (byte[]) getValue(); 055 return (value != null ? new String(value) : ""); 056 } 057 058}