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 com.foxinmy.weixin4j.http.apache.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 com.foxinmy.weixin4j.http.ContentType;
37 import com.foxinmy.weixin4j.http.apache.mime.MIME;
38
39
40
41
42
43
44
45
46 public class FileBody extends AbstractContentBody {
47
48 private final File file;
49 private final String filename;
50
51
52
53
54
55 public FileBody(final File file, final String filename,
56 final String mimeType, final String charset) {
57 this(file, ContentType.create(mimeType, charset), filename);
58 }
59
60
61
62
63
64 public FileBody(final File file, final String mimeType, final String charset) {
65 this(file, null, mimeType, charset);
66 }
67
68
69
70 public FileBody(final File file, final String mimeType) {
71 this(file, ContentType.create(mimeType), null);
72 }
73
74 public FileBody(final File file) {
75 this(file, ContentType.DEFAULT_BINARY, file != null ? file.getName()
76 : null);
77 }
78
79
80
81
82 public FileBody(final File file, final ContentType contentType,
83 final String filename) {
84 super(contentType);
85 this.file = file;
86 this.filename = filename == null ? file.getName() : filename;
87 }
88
89
90
91
92 public FileBody(final File file, final ContentType contentType) {
93 this(file, contentType, file != null ? file.getName() : null);
94 }
95
96 public InputStream getInputStream() throws IOException {
97 return new FileInputStream(this.file);
98 }
99
100 @Override
101 public void writeTo(final OutputStream out) throws IOException {
102 final InputStream in = new FileInputStream(this.file);
103 try {
104 final byte[] tmp = new byte[4096];
105 int l;
106 while ((l = in.read(tmp)) != -1) {
107 out.write(tmp, 0, l);
108 }
109 out.flush();
110 } finally {
111 in.close();
112 }
113 }
114
115 @Override
116 public String getTransferEncoding() {
117 return MIME.ENC_BINARY;
118 }
119
120 @Override
121 public long getContentLength() {
122 return this.file.length();
123 }
124
125 @Override
126 public String getFilename() {
127 return filename;
128 }
129
130 public File getFile() {
131 return this.file;
132 }
133
134 }