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