001/* 002 * Copyright 2002-2012 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.beans.PropertyEditorSupport; 020import java.io.IOException; 021 022import org.springframework.web.multipart.MultipartFile; 023 024/** 025 * Custom {@link java.beans.PropertyEditor} for converting 026 * {@link MultipartFile MultipartFiles} to Strings. 027 * 028 * <p>Allows one to specify the charset to use. 029 * 030 * @author Juergen Hoeller 031 * @since 13.10.2003 032 */ 033public class StringMultipartFileEditor extends PropertyEditorSupport { 034 035 private final String charsetName; 036 037 038 /** 039 * Create a new {@link StringMultipartFileEditor}, using the default charset. 040 */ 041 public StringMultipartFileEditor() { 042 this.charsetName = null; 043 } 044 045 /** 046 * Create a new {@link StringMultipartFileEditor}, using the given charset. 047 * @param charsetName valid charset name 048 * @see java.lang.String#String(byte[],String) 049 */ 050 public StringMultipartFileEditor(String charsetName) { 051 this.charsetName = charsetName; 052 } 053 054 055 @Override 056 public void setAsText(String text) { 057 setValue(text); 058 } 059 060 @Override 061 public void setValue(Object value) { 062 if (value instanceof MultipartFile) { 063 MultipartFile multipartFile = (MultipartFile) value; 064 try { 065 super.setValue(this.charsetName != null ? 066 new String(multipartFile.getBytes(), this.charsetName) : 067 new String(multipartFile.getBytes())); 068 } 069 catch (IOException ex) { 070 throw new IllegalArgumentException("Cannot read contents of multipart file", ex); 071 } 072 } 073 else { 074 super.setValue(value); 075 } 076 } 077 078}