接口声明
这个接口的参数描述还算详细。主要是用了Swagger的注解@ApiParam。
@RestController
@RequestMapping("/upload")
@Api(tags="文件上传")
public class AliyunOssController {
@Autowired
UploadService service;
@PostMapping(value = "/comment/{bId}/{uId}")
@ApiOperation(value = "上传评论图片或视频,成功后返回文件路径",notes = "/upload/comment/板块ID/用户ID")
public JSONObject comment(@ApiParam(value = "版块ID", required = true) @PathVariable String bId,
@ApiParam(value = "用户ID", required = true) @PathVariable String uId,
@ApiParam(value = "文件", required = true) @RequestParam(value="f") MultipartFile file) {
String url = service.upload(bId,uId,file);
……
JSONObject jo = new JSONObject();
jo.put("code",200);
jo.put("msg","ok");
jo.put("data",url);
return jo;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
接口实现
@Service("uploadService")
public class UploadService {
public String upload(String bId,
String uId,
MultipartFile file) {
//获得文件保存路径
String url = getFilePath(bId, uId, file);
saveToLocal(file);
return url;
}
private void saveToLocal(MultipartFile file){//上传到本地
try {
String fileName = file.getOriginalFilename();
InputStream input = file.getInputStream();
OutputStream outputStream = new FileOutputStream("q:" + File.separator + fileName);
byte[] b = new byte[4096];
int count = input.read(b);
while (count != -1) {
for(int i = 0; i < count; i++){
outputStream.write(b[i]);
}
count = input.read(b);
}
input.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32