最近学习了一个上传本地文件(.jpg、.png、.txt、.doc、.html、.jsp等等格式)到远程服务器的功能。
写此功能自然想到了ajax的异步上传、token验证了。
可以先写一个测试类,此处我就不写了,直接贴controller层上传代码了。
/**
* 上传文件
*/
@RequestMapping("/postFile")
@ResponseBody
public Object postFile(HttpServletRequest request, @RequestParam("file")MultipartFile file) {
Map<String, String> map = new HashMap<String, String>();
if (!file.isEmpty()) {
//获取文件名
String fname = file.getOriginalFilename();
//获取文件路径
String suffix = comonUtil.getFileTypeExts(fname);//文件后缀
String furl = UUID.randomUUID().toString() + suffix;
map.put("fname", fname);
map.put("furl", furl);
String path = this.servletContext.getRealPath("/resource/"+fname);
File tempFile = new File(path); //将上传文件放到临时的resource目录下。
try {
file.transferTo(tempFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int res_code = postFile2Remote(furl, tempFile); //调用postFile2Remote方法
if(res_code != 200){ //如果res_code=200(响应代码)时,上传成功。
//失败
}
tempFile.delete();
}
return map;
}
/**
* 上传文件至远程服务器
*/
public int postFile2Remote(String uuidName, File file){
int code =500;
CloseableHttpClient httpclient = HttpClients.createDefault(); //创建一个httpclient
try {
HttpPost httppost = new HttpPost(Constant.REMOTE_FILESERVER_UPLOAD_URL);
//REMOTE_FILESERVER_UPLOAD_URL此路径写在Constant类里面。
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("token", new StringBody(Constant.REMOTE_FILESERVER_TOKEN,ContentType.TEXT_PLAIN))//token验证
.addPart("path", new StringBody("qgg",ContentType.TEXT_PLAIN))
.addPart("fileName", new StringBody(uuidName,ContentType.TEXT_PLAIN))
.addPart("bin", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM,file.getName()))
.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
EntityUtils.consume(response.getEntity());
code = response.getStatusLine().getStatusCode();
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return code;
}
效果如下: