ps:百度程序员请直接C/V,一键三连,秒解,请秒懂!
前端自行收拾,不用使用form-date格式,直接请求就行
上代码
1.controller
@PostMapping(value = "/uploadImgNotLogin")
@ResponseBody
@ApiOperation(value = "头像上传(上传图片)", notes = "data-form格式;返回上传路径;参数loginUid :接口uid String;file 文件图片")
public Result uploadImgNotLogin(@ApiParam("文件") @RequestParam(value = "file", required = false) MultipartFile file) {
if (file.isEmpty()) {
return Result.defaultResult(ResultCode.FAIL, "上传失败,请选择文件!", null);
}
String fileName = file.getOriginalFilename();
File upload = UploadUtils.getFileDir(String.valueOf(99999));
File dest = new File(upload, fileName);
try {
file.transferTo(dest);
System.out.println("上传成功");
System.out.println(FileSrcConstantValue.WJSRC + "99999" + "/images/" + fileName);
return Result.defaultResult(ResultCode.SUCCESS, "上传成功!", FileSrcConstantValue.WJSRC + "99999" + "/images/" + fileName);
} catch (IOException e) {
System.out.println(e);
}
return Result.defaultResult(ResultCode.FAIL, "上传失败!", null);
}
2.utils(注意这是linux服务器路径)
public class FileSrcConstantValue {
public static String WJSRC = "/file/";
}
public class UploadUtils {
public static File getFileDir(String userId) {
String filePath = FileSrcConstantValue.WJSRC;
String childPath = userId+"/images/";
//如果上传目录为/static/images/upload/,则可以如下获取
File upload=new File(filePath,childPath);
if(!upload.exists()){
upload.mkdirs();
}
System.out.println(upload.getAbsolutePath());
return upload;
}
3.统一返回处理
public class Result<T> {
private int code;
private String message;
private T data;
public Result setCode(ResultCode resultCode) {
this.code = resultCode.code();
return this;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public Result setMessage(String message) {
this.message = message;
return this;
}
public T getData() {
return data;
}
public Result setData(T data) {
this.data = data;
return this;
}
public Result() {
}
public Result(ResultCode resultCode, String msg, Object obj) {
this.code = resultCode.code();
this.message = msg;
if (obj != null) {
this.data = (T) obj;
}
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
/** 统一返回 **/
public static Result result(ResultCode resultCode,Object obj) {
return new Result(resultCode, "操作成功", obj);
}
public static Result defaultResult(ResultCode resultCode,String msg,Object obj) {
return new Result(resultCode, msg, obj);
}
}