首页 > 代码库 > 文件上传
文件上传
1: package com.jb.android.upload;
2:
3: import java.io.BufferedReader;
4: import java.io.InputStreamReader;
5: import java.io.OutputStream;
6: import java.io.RandomAccessFile;
7: import java.net.InetAddress;
8: import java.net.Socket;
9: import java.net.URL;
10: import java.util.Map;
11:
12: import com.jb.util.json.JsonBinder;
13:
14: /**
15: * 文件上传线程
16: *
17: * @author dmx
18: *
19: */
20: public class UploadThread extends Thread {
21: private String path;
22: private Map<String, String> params;
23: private FormFile uploadFile;
24: private int start;
25: private int end;
26: private int threadId;
27: private FileUploader uploader;
28: private boolean finished = false;
29: private int uploadedLength = 0;
30:
31: /**
32: * 文件上传是否已经完成
33: */
34: public boolean isFinished() {
35: return finished;
36: }
37:
38: /**
39: * 获取已经上传的文件的大小
40: */
41: public int getUploadedLength() {
42: return uploadedLength;
43: }
44:
45: public UploadThread(FileUploader uploader, String url,
46: Map<String, String> params, FormFile file, int threadId, int start,
47: int position, int end, int fileSize) {
48: this.uploader = uploader;
49: this.path = url;
50: this.params = params;
51: this.uploadFile = file;
52: this.threadId = threadId;
53: this.start = position;
54: this.end = end;
55: params.put("threadID", threadId + "");
56: params.put("start", start + "");
57: params.put("position", position + "");
58: if (end >= fileSize) {
59: end = fileSize - 1;
60: }
61: params.put("end", end + "");
62: params.put("fileSize", fileSize + "");
63:
64: }
65:
66: @Override
67: public void run() {
68: OutputStream outStream = null;
69: Socket socket = null;
70: BufferedReader reader = null;
71: try {
72: final String BOUNDARY = "---------------------------7da2137580612"; // 数据分隔线
73: final String endline = "--" + BOUNDARY + "--\r\n";// 数据结束标志
74:
75: int fileDataLength = 0;
76: StringBuilder fileExplain = new StringBuilder();
77: fileExplain.append("--");
78: fileExplain.append(BOUNDARY);
79: fileExplain.append("\r\n");
80: fileExplain.append("Content-Disposition: form-data;name=\""
81: + uploadFile.getParameterName() + "\";filename=\""
82: + uploadFile.getFilname() + "\"\r\n");
83: fileExplain.append("Content-Type: " + uploadFile.getContentType()
84: + "\r\n\r\n");
85: fileExplain.append("\r\n");
86: fileDataLength += fileExplain.toString().getBytes().length;
87: fileDataLength += end - start + 1;
88: StringBuilder textEntity = new StringBuilder();
89: for (Map.Entry<String, String> entry : params.entrySet()) {// 构造文本类型参数的实体数据
90: textEntity.append("--");
91: textEntity.append(BOUNDARY);
92: textEntity.append("\r\n");
93: textEntity.append("Content-Disposition: form-data; name=\""
94: + entry.getKey() + "\"\r\n\r\n");
95: textEntity.append(entry.getValue());
96: textEntity.append("\r\n");
97: }
98: StringBuilder appendParameter = new StringBuilder();
99: appendParameter.append("--");
100: appendParameter.append(BOUNDARY);
101: appendParameter.append("\r\n");
102: appendParameter.append("Content-Disposition: form-data; name=\""
103: + "Upload" + "\"\r\n\r\n");
104: appendParameter.append("Submit Query");
105: appendParameter.append("\r\n");
106: // 计算传输给服务器的实体数据总长度
107: int dataLength = textEntity.toString().getBytes().length
108: + fileDataLength + endline.getBytes().length
109: + appendParameter.toString().length();
110: URL url = new URL(path);
111: int port = url.getPort() == -1 ? 80 : url.getPort();
112: socket = new Socket(InetAddress.getByName(url.getHost()), port);
113: outStream = socket.getOutputStream();
114: // 下面完成HTTP请求头的发送
115: String requestmethod = "POST " + url.getPath() + " HTTP/1.1\r\n";
116: outStream.write(requestmethod.getBytes());
117: String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
118: outStream.write(accept.getBytes());
119: String language = "Accept-Language: zh-CN\r\n";
120: outStream.write(language.getBytes());
121: String contenttype = "Content-Type: multipart/form-data; boundary="
122: + BOUNDARY + "\r\n";
123: outStream.write(contenttype.getBytes());
124: String contentlength = "Content-Length: " + dataLength + "\r\n";
125: outStream.write(contentlength.getBytes());
126: String alive = "Connection: Keep-Alive\r\n";
127: outStream.write(alive.getBytes());
128: String host = "Host: " + url.getHost() + ":" + port + "\r\n";
129: outStream.write(host.getBytes());
130: // 写完HTTP请求头后根据HTTP协议再写一个回车换行
131: outStream.write("\r\n".getBytes());
132:
133: // 把所有文本类型的实体数据发送出来
134: outStream.write(textEntity.toString().getBytes());
135: StringBuilder fileEntity = new StringBuilder();
136: fileEntity.append("--");
137: fileEntity.append(BOUNDARY);
138: fileEntity.append("\r\n");
139: fileEntity.append("Content-Disposition: form-data;name=\""
140: + uploadFile.getParameterName() + "\";filename=\""
141: + uploadFile.getFilname() + "\"\r\n");
142: fileEntity.append("Content-Type: " + uploadFile.getContentType()
143: + "\r\n\r\n");
144: outStream.write(fileEntity.toString().getBytes());
145: int bufferSize = 1024;
146: byte[] buffer = new byte[bufferSize];
147: int count = 0;
148: RandomAccessFile file = new RandomAccessFile(uploadFile.getFile(),
149: "r");
150: file.seek(start);
151: int length = end - start + 1;// 计算读取的长度
152: while (!uploader.getExited() && length > 0) {// 将指定位置和长度的文件流写入到服务器
153: count = file.read(buffer);
154: if (count <= 0) {
155: break;
156: }
157: if (length < count) {// 剩余长度不足n
158:
159: outStream.write(buffer, 0, length);
160: uploadedLength += length;
161: } else {
162: outStream.write(buffer, 0, count);
163: uploadedLength += count;
164: }
165: length -= count;// 剩余长度
166: uploader.appendUploadSize(threadId, uploadedLength);
167: }
168: outStream.write("\r\n".getBytes());
169: outStream.write(appendParameter.toString().getBytes());
170: // 下面发送数据结束标志,表示数据已经结束
171: byte[] bytes = endline.getBytes();
172: outStream.write(bytes, 0, bytes.length);
173:
174: reader = new BufferedReader(new InputStreamReader(
175: socket.getInputStream()));
176: String line = reader.readLine();
177: // System.out.println(line);
178: // 读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
179: if (line.indexOf("200") == -1) {
180: throw new Exception("上传失败:" + line);
181: }
182: while ((line = reader.readLine()) != null) {
183: if (line.startsWith("{") && line.endsWith("}")) {
184: Map res = JsonBinder.getJsonBinder()
185: .toBean(line, Map.class);
186: if (res.get("success").toString().equals("true")) {
187: uploader.setReturnValue(res);
188: }
189: }
190: // System.out.println(line);
191: }
192:
193: outStream.flush();
194: finished = true;
195: } catch (Exception ex) {
196: uploadedLength = -1;
197: uploader.appendUploadSize(threadId, 0);
198: ex.printStackTrace();
199: } finally {
200: try {
201: if (outStream != null) {
202: outStream.close();
203: }
204:
205: } catch (Exception e) {
206: e.printStackTrace();
207: }
208: try {
209: if (reader != null) {
210: reader.close();
211: }
212:
213: } catch (Exception e) {
214: e.printStackTrace();
215: }
216: try {
217: if (socket != null) {
218: socket.close();
219: }
220: } catch (Exception e) {
221: e.printStackTrace();
222: }
223: }
224:
225: }
226: }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。