1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.http.entity.mime.content;
29
30 import java.io.File;
31 import java.io.FileInputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.OutputStream;
35
36 import org.apache.http.entity.mime.MIME;
37
38
39
40
41
42 public class FileBody extends AbstractContentBody {
43
44 private final File file;
45 private final String filename;
46 private final String charset;
47
48
49
50
51 public FileBody(final File file,
52 final String filename,
53 final String mimeType,
54 final String charset) {
55 super(mimeType);
56 if (file == null) {
57 throw new IllegalArgumentException("File may not be null");
58 }
59 this.file = file;
60 if (filename != null)
61 this.filename = filename;
62 else
63 this.filename = file.getName();
64 this.charset = charset;
65 }
66
67
68
69
70 public FileBody(final File file,
71 final String mimeType,
72 final String charset) {
73 this(file, null, mimeType, charset);
74 }
75
76 public FileBody(final File file, final String mimeType) {
77 this(file, mimeType, null);
78 }
79
80 public FileBody(final File file) {
81 this(file, "application/octet-stream");
82 }
83
84 public InputStream getInputStream() throws IOException {
85 return new FileInputStream(this.file);
86 }
87
88 public void writeTo(final OutputStream out) throws IOException {
89 if (out == null) {
90 throw new IllegalArgumentException("Output stream may not be null");
91 }
92 InputStream in = new FileInputStream(this.file);
93 try {
94 byte[] tmp = new byte[4096];
95 int l;
96 while ((l = in.read(tmp)) != -1) {
97 out.write(tmp, 0, l);
98 }
99 out.flush();
100 } finally {
101 in.close();
102 }
103 }
104
105 public String getTransferEncoding() {
106 return MIME.ENC_BINARY;
107 }
108
109 public String getCharset() {
110 return charset;
111 }
112
113 public long getContentLength() {
114 return this.file.length();
115 }
116
117 public String getFilename() {
118 return filename;
119 }
120
121 public File getFile() {
122 return this.file;
123 }
124
125 }