------------------------- 前端页面 -----------------------
<script type="text/javascript" src="/x5/js/lib/jquery/jquery.form.js"></script>
<form id="kfkForm" method="post" action="" enctype="multipart/form-data">
<table class="table-form">
<tr group="0">
<th width="15%" ng-if="permission.fields.KfkConfig.CONFIGNAME_!='n'">
CONFIGNAME_
</th>
<td width="35%" ng-if="permission.fields.KfkConfig.CONFIGNAME_!='n'">
<input name="CONFIGNAME_" class="form-control" type="text" />
</td>
<th width="15%" ng-if="permission.fields.KfkConfig.FILEPATH_!='n'">
FILEPATH_
</th>
<td width="50%" colspan="2">
<input type="file" id="uFile" class="form-control" name="uFile"/>
</td>
<td width="15%">
<button onclick="config('download')" style="color:red;">从KFK服务器下载配置文件</button> <button onclick="config('upload')" style="color:red;">上传配置文件到KFK服务器</button>
</td>
</tr></table>
</form>
function config(type){
var url = "/x5/form/table/kfkConfigUpload";
if(type == 'download' ){
url = "/x5/form/table/kfkConfigDownload"
location.href=url+"?"+$("#kfkForm").serialize();
}else // 需要用到 ajaxSubmit提交file内容
var option = {
type: "POST",
url: url,
data: {
'type': type
},
success:function(data){
}
};
$("#kfkForm").ajaxSubmit(option);
}
------------------------- controller -------------------------
/**
* 根据上传文件
* 修改KFK配置;
需要用注解方式获取FILE二进制内容
* @param request
* @param response
*/
@RequestMapping(value = "kfkConfigUpload" , method = RequestMethod.POST)
public void kfkConfigUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam("uFile") MultipartFile uFile ) throws Exception {
ResultMessage message = null;
Object params = null;
try {
Map<String, String> map =new HashMap<>();
Enumeration<String> er = request.getParameterNames();
while (er.hasMoreElements()) {
String name = (String) er.nextElement();
String value = request.getParameter(name);
map.put(name, value);
}
CommonDao commonDao = AppUtil.getBean(CommonDao.class);
String type = map.get("type");
ConfigFileInfo fileInfo = new ConfigFileInfo();
HttpPostUtils ups = new HttpPostUtils();
fileInfo.setClientUrl(map.get("URL_"));
fileInfo.setConfigName(map.get("CONFIGNAME_"));
String p = request.getSession().getServletContext().getRealPath("");
String fPath = p.substring(0, p.indexOf("x5")+2) + "\\" + uFile.getOriginalFilename();
fileInfo.setTempFilePath(fPath);
File path = new File(fPath);
FileOutputStream outputStream = new FileOutputStream(path);
outputStream.write(uFile.getBytes());
outputStream.close();
ups.postFile( fileInfo );
} catch (Exception e) {
e.printStackTrace();
message = new ResultMessage(ResultMessage.FAIL, e.getCause().getMessage() );
} finally {
writeResultMessage(response.getWriter(), message);
}
}
/**
* 下载KFK配置;
* @param request
* @param response
*/
@RequestMapping(value = "kfkConfigDownload")
public void kfkConfigDownload(HttpServletRequest request, HttpServletResponse response ) throws Exception {
ResultMessage message = null;
BufferedInputStream dis = null;
BufferedOutputStream fos = null;
Object params = null;
try {
Map<String, String> map =new HashMap<>();
Enumeration<String> er = request.getParameterNames();
while (er.hasMoreElements()) {
String name = (String) er.nextElement();
String value = request.getParameter(name);
map.put(name, value);
}
CommonDao commonDao = AppUtil.getBean(CommonDao.class);
ConfigFileInfo fileInfo = new ConfigFileInfo();
HttpPostUtils ups = new HttpPostUtils();
fileInfo.setClientUrl(map.get("URL_"));
fileInfo.setConfigName(map.get("CONFIGNAME_"));
String p = request.getSession().getServletContext().getRealPath("");
String fPath = p.substring(0, p.indexOf("x5")+2) + "\\" ;
fileInfo.setTempFilePath(fPath);
String fileName = ups.downloadFile( fileInfo );
message = new ResultMessage(ResultMessage.SUCCESS, fPath+fileName );
File file = new File(fPath+fileName);
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
dis = new BufferedInputStream( new FileInputStream(file) );
fos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
fos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
message = new ResultMessage(ResultMessage.FAIL, e.getCause().getMessage() );
} finally {
if (dis != null)
try{
dis.close();
}catch (Exception e){
e.printStackTrace();
}
if (fos != null)
try{
fos.close();
}catch (Exception e){
e.printStackTrace();
}
writeResultMessage(response.getWriter(), message);
}
}
------------------------- 工具类 -------------------------
public static void postFile(ConfigFileInfo fileInfo) {
PostMethod filePost = new PostMethod(fileInfo.getClientUrl() + "/uploadConfigFile");
File tmpfile = new File(fileInfo.getTempFilePath());
if (!tmpfile.exists()) {
logger.error("temp file is not found!");
return;
}
if ( StringUtil.isEmpty(fileInfo.getClientUrl())) {
logger.error("client url is empty!");
return;
}
if ( StringUtil.isEmpty(fileInfo.getConfigName())) {
logger.error("config name is not setup!");
return;
}
try {
Part[] parts = { new FilePart("file", tmpfile),
new StringPart("configName", fileInfo.getConfigName()) };
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
String responseMsg = new String(filePost.getResponseBody(),"utf-8");
System.out.println(responseMsg);
// 上传成功
} else {
System.out.println("上传失败");
// 上传失败
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
}
public static String downloadFile(ConfigFileInfo fileInfo) {
String fileName = "";
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(fileInfo.getClientUrl() + "/getConfigFile");
client.getHttpConnectionManager().getParams().setConnectionTimeout(1000 * 60 * 5);
client.getHttpConnectionManager().getParams().setSoTimeout(1000 * 60 * 10);
try {
method.setParameter("configName", fileInfo.getConfigName());
//method.setDoAuthentication(true);
int status = client.executeMethod(method);
if (status != 200) {
throw new RuntimeException("the status is " + status);
}
InputStream input = method.getResponseBodyAsStream();
Header[] hs = method.getResponseHeaders();
for (Header h : hs) {
System.out.println(h.getName() + ":" + h.getValue());
if(h.getValue().indexOf("filename=")>-1){
fileName = h.getValue().substring(h.getValue().indexOf("=")+1);
}
}
OutputStream out = new FileOutputStream(new File(fileInfo.getTempFilePath()+fileName));
int length = 0;
byte [] rbody = new byte[1024];
int readNum = 0;
while ((readNum = input.read(rbody)) > 0) {
out.write(rbody,0,readNum);
length += readNum;
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
return fileName;
}
05-23
03-04
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交