parent
0aaa415e5e
commit
77bcb17e8e
@ -0,0 +1,63 @@
|
||||
package com.example.flower.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.example.flower.unit.JWTUtil;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/upload")
|
||||
public class UploadController {
|
||||
|
||||
@Value("${web.upload-path}")
|
||||
String uploadPath;
|
||||
//上传图片
|
||||
@PostMapping("")
|
||||
public JSONObject upload(@RequestHeader String Authorization,@RequestParam("file") MultipartFile file){
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
|
||||
if(!JWTUtil.checkToken(Authorization)){ //token认证失败
|
||||
JWTUtil.checkTokenFailed(jsonObject);
|
||||
return jsonObject;
|
||||
}
|
||||
Claims body= JWTUtil.getBodyByToken(Authorization);
|
||||
int id = (int) body.get("id");
|
||||
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
File rootDir = new File(uploadPath);
|
||||
if(!rootDir.exists()){
|
||||
rootDir.mkdir();
|
||||
}
|
||||
File userDir = new File(uploadPath+"/"+id);
|
||||
if(!userDir.exists()){
|
||||
userDir.mkdir();
|
||||
}
|
||||
String dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
|
||||
String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
|
||||
File addFile = new File(userDir,dateFormat + type);
|
||||
OutputStream outputStream = Files.newOutputStream(addFile.toPath());
|
||||
outputStream.write(file.getBytes());
|
||||
|
||||
jsonObject.put("code",200);
|
||||
jsonObject.put("msg","成功");
|
||||
|
||||
json.put("url","/"+id+ "/" + dateFormat + type);
|
||||
|
||||
jsonObject.put("data",json);
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
jsonObject.put("code",403);
|
||||
jsonObject.put("msg","失败");
|
||||
}
|
||||
return jsonObject;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in new issue