01: /*
02: * Copyright 2002-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.web.multipart.support;
18:
19: import java.beans.PropertyEditorSupport;
20: import java.io.IOException;
21:
22: import org.apache.commons.logging.Log;
23: import org.apache.commons.logging.LogFactory;
24:
25: import org.springframework.web.multipart.MultipartFile;
26:
27: /**
28: * Custom {@link java.beans.PropertyEditor} for converting
29: * {@link org.springframework.web.multipart.MultipartFile MultipartFiles}
30: * to Strings.
31: *
32: * <p>Allows one to specify the charset to use.
33: *
34: * @author Juergen Hoeller
35: * @since 13.10.2003
36: */
37: public class StringMultipartFileEditor extends PropertyEditorSupport {
38:
39: /** Static to avoid creating a new logger every time */
40: private static final Log logger = LogFactory
41: .getLog(StringMultipartFileEditor.class);
42:
43: private final String charsetName;
44:
45: /**
46: * Create a new {@link StringMultipartFileEditor}, using the default charset.
47: */
48: public StringMultipartFileEditor() {
49: this .charsetName = null;
50: }
51:
52: /**
53: * Create a new {@link StringMultipartFileEditor}, using the given charset.
54: * @param charsetName valid charset name
55: * @see java.lang.String#String(byte[],String)
56: */
57: public StringMultipartFileEditor(String charsetName) {
58: this .charsetName = charsetName;
59: }
60:
61: public void setAsText(String text) {
62: setValue(text);
63: }
64:
65: public void setValue(Object value) {
66: if (value instanceof MultipartFile) {
67: MultipartFile multipartFile = (MultipartFile) value;
68: try {
69: super .setValue(this .charsetName != null ? new String(
70: multipartFile.getBytes(), this .charsetName)
71: : new String(multipartFile.getBytes()));
72: } catch (IOException ex) {
73: logger.warn("Cannot read contents of multipart file",
74: ex);
75: throw new IllegalArgumentException(
76: "Cannot read contents of multipart file: "
77: + ex.getMessage());
78: }
79: } else {
80: super.setValue(value);
81: }
82: }
83:
84: }
|