result 是自己定义的一个返回对象,后面有贴代码片。
/**
* 控制层代码
* 上传文件
* @return
* @throws IOException
*/
@RequestMapping("uploadFile")
public Result uploadFile(@AuthenticationPrincipal SecurityUser user,MultipartFile file) throws IOException{
return menuService.uploadFile(file, getMd5ByBytes(file.getBytes()));
}
private String getMd5ByBytes(byte[] data) {
String value = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(data);
BigInteger bi = new BigInteger(1, md5.digest());
value = bi.toString(16);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return value;
}
//service 代码片
public Result uploadFile(MultipartFile file,String MD5){
String rsp = "";
try {
//http://api.file.oss.xxxx.com/upload
rsp = ConnectionTools.doPostForFile("上传接口地址", file, MD5);
JSONObject jsonObj = JSONObject.fromObject(rsp);
if(jsonObj.getInt("code") == 1){
String shortId = jsonObj.getString("data");
return new Result(0,"文件上传成功",shortId);
}else{
return new Result(1,"文件上传失败");
}
} catch (Exception e) {
return new Result(1,"文件上传失败");
}
}
//service 上传工具代码片
public static String doPostForFile(String url, MultipartFile file, String MD5) {
// 响应内容
String result = "";
// 定义http客户端对象--httpClient
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(1000*8);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000*8);
// 定义并实例化客户端链接对象-postMethod
PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
try {
// 设置http的头
postMethod.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
StringPart stringpart = new StringPart("MD5", MD5);
byte[] buffer = file.getBytes();
FilePart filepart = new FilePart("file", new ByteArrayPartSource("file", buffer));
MultipartRequestEntity mrp = new MultipartRequestEntity(new Part[] { stringpart, filepart },postMethod.getParams());
postMethod.setRequestEntity(mrp);
// 定义访问地址的链接状态
int statusCode = 0;
try {
// 客户端请求url数据
statusCode = httpClient.executeMethod(postMethod);
} catch (Exception e) {
e.printStackTrace();
}
// 请求成功状态-200
// if (statusCode == HttpStatus.SC_OK) {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(postMethod.getResponseBodyAsStream(), "utf-8"));
String msg = null;
while ((msg = reader.readLine()) != null) {
result += msg;
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
// } else {
System.out.println(result);
if (statusCode != HttpStatus.SC_OK) {
result = "";
}
// }
} catch (Exception e) {
e.getMessage();
} finally {
// 释放链接
postMethod.releaseConnection();
httpClient.getHttpConnectionManager().closeIdleConnections(0);
}
return result;
}
result 代码片
public class Result implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 0:正确
* 1:业务异常
* 2:数据格式异常
* 3:token失效
* ...
*/
protected Integer code = 0;
/**
* 返回的结果信息
*/
protected String msg = "";
/**
* 扩展信息
*/
protected Object ext = "";
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getExt() {
return ext;
}
public void setExt(Object ext) {
this.ext = ext;
}
/**
* 构造函数
* @param code
* @param msg
* @param data
*/
public Result(Integer code,String msg){
this.code = code;
this.msg = msg;
}
public Result(Integer code,String msg,Object ext,long total){
Map<String,Object> t = new ConcurrentHashMap<>();
t.put("total", total);
t.put("data", ext);
this.ext = t;
}
public Result(BindingResult result){
this.code=2;
this.msg="数据格式错误";
if(result.hasErrors())
{
List<FieldError> list = result.getFieldErrors();
List<Map<String,String>> _tempList = new ArrayList<Map<String,String>>(0);
for(int i = 0 ; i < list.size(); i++)
{
FieldError fieldError = list.get(i);
Map<String,String> __tempMap = new HashMap<String,String>(0);
__tempMap.put("field", fieldError.getField());
__tempMap.put("error", fieldError.getDefaultMessage());
_tempList.add(__tempMap);
}
this.ext = _tempList;
}
}
/**
* 构造函数
* @param code
* @param msg
* @param data
*/
public Result(Integer code,String msg,Object ext){
this.msg = msg;
this.ext = ext;
}
/**
* 无参构造函数
*/
public Result(){
}
}