/
UploadController.java
71 lines (66 loc) · 2.83 KB
/
UploadController.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2019-2020 十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.newbee.mall.controller.common;
import ltd.newbee.mall.common.Constants;
import ltd.newbee.mall.util.NewBeeMallUtils;
import ltd.newbee.mall.util.Result;
import ltd.newbee.mall.util.ResultGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@Controller
@RequestMapping("/admin")
public class UploadController {
@PostMapping({"/upload/file"})
@ResponseBody
public Result upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws URISyntaxException {
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//生成文件名称通用方法
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
Random r = new Random();
StringBuilder tempName = new StringBuilder();
tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
String newFileName = tempName.toString();
File fileDirectory = new File(Constants.FILE_UPLOAD_DIC);
//创建文件
File destFile = new File(Constants.FILE_UPLOAD_DIC + newFileName);
try {
if (!fileDirectory.exists()) {
if (!fileDirectory.mkdir()) {
throw new IOException("文件夹创建失败,路径为:" + fileDirectory);
}
}
file.transferTo(destFile);
Result resultSuccess = ResultGenerator.genSuccessResult();
resultSuccess.setData(NewBeeMallUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/upload/" + newFileName);
return resultSuccess;
} catch (IOException e) {
e.printStackTrace();
return ResultGenerator.genFailResult("文件上传失败");
}
}
}