private
boolean
uploadFile(String type, String file_name) {
URL url =
null
;
HttpURLConnection hc =
null
;
byte
[] raw =
null
;
FileInputStream in =
null
;
File file =
null
;
try
{
file =
new
File(file_name);
long
file_size =
0
;
if
(file.exists()) {
file_size = file.length();
}
in =
new
FileInputStream(file_name);
raw =
new
byte
[Integer.parseInt(String.valueOf(file_size))];
int
i =
0
;
int
index =
0
;
while
((i = in.read()) != -
1
) {
raw[index++] = (
byte
) i;
}
}
catch
(IOException e) {
e.printStackTrace();
return
false
;
}
finally
{
try
{
if
(in !=
null
) {
in.close();
}
}
catch
(Exception e) {
}
}
MimetypesFileTypeMap file_type_map =
new
MimetypesFileTypeMap();
String mine_type = file_type_map.getContentType(file);
String remoe_folder =
"x:"
+ File.separator +
"Image"
;
String remoe_up_http_url =
""
;
try
{
remoe_up_http_url =
"http://xxx.xxx.xxx/fckeditor/editor/filemanager/browser/default/connectors/jsp/connector?Command=FileUpload&Type="
+ type
+
"&CurrentFolder="
+ URLEncoder.encode(remoe_folder,
"UTF-8"
);
url =
new
URL(remoe_up_http_url);
String BOUNDARY =
"---------------------------7d33a816d302b6"
;
// separate line
String MULTIPART_FORM_DATA =
"multipart/form-data"
;
StringBuffer sb =
new
StringBuffer();
sb = sb.append(
"--"
);
sb = sb.append(BOUNDARY);
sb = sb.append(
"\r\n"
);
sb = sb
.append(
"Content-Disposition:form-data;name=\"NewFile\";filename=\""
+ file_name +
"\"\r\n"
);
sb = sb.append(
"Content-Type:"
);
sb = sb.append(mine_type);
sb = sb.append(
"\r\n\r\n"
);
byte
[] data = sb.toString().getBytes(
"UTF-8"
);
byte
[] end_data = (
"\r\n--"
+ BOUNDARY +
"--\r\n"
).getBytes();
hc = (HttpURLConnection) url.openConnection();
// set HTTP head:
hc.setRequestProperty(
"Content-Type"
, MULTIPART_FORM_DATA
+
";boundary="
+ BOUNDARY);
hc.setRequestProperty(
"Content-Length"
, String.valueOf(data.length
+ raw.length + end_data.length));
hc.setRequestMethod(
"POST"
);
hc.setDoOutput(
true
);
hc.setDoInput(
true
);
hc.getOutputStream().write(data);
hc.getOutputStream().write(raw,
0
, raw.length);
hc.getOutputStream().write(end_data);
hc.getOutputStream().close();
int
cah = hc.getResponseCode();
if
(cah != HttpURLConnection.HTTP_OK) {
System.out.println(cah);
return
false
;
}
// 定义输入流
InputStream instream = hc.getInputStream();
BufferedReader br =
new
BufferedReader(
new
InputStreamReader(
instream,
"UTF-8"
));
String content =
""
;
String line = br.readLine();
while
(line !=
null
) {
content += line +
"\n"
;
line = br.readLine();
}
System.out.println(content);
if
(content
.indexOf(
"window.parent.frames['frmUpload'].OnUploadCompleted(203,"
) >
0
) {
//上传失败
return
false
;
}
return
true
;
}
catch
(Exception e) {
e.printStackTrace();
return
false
;
}
finally
{
try
{
hc.getOutputStream().close();
}
catch
(Exception e) {
}
hc.disconnect();
}
}