/**
* 端口号
*/
@Value("8083")
private int serverPort;
/**
* 文件上传路径
*/
@Value("D://img")
private String dir;
/**
* @Description 文件单个上传
* @param file
*/
@ResponseBody
@RequestMapping(value="/upload")
public ResponseObject upload(@RequestParam(value="file") MultipartFile file, HttpServletRequest request) {
try {
if(file != null) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = format.format(new Date());
File fileDir = new File(dir+File.separator+date);
if(!fileDir.exists()) {//文件夹不存在先创建
fileDir.mkdirs();
}
String code = RandomCodeUtil.getRandomNum(15);
String suf = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
file.transferTo(new File(dir+File.separator+date+File.separator+code+suf));
Map<String, Object> resMap = new HashMap<String, Object>();
String address = InetAddress.getLocalHost().getHostAddress();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("http://").append(address).append(":").append(serverPort)
.append("/event/open/api/").append(date).append("/").append(code).append(suf);
// stringBuffer.append("http://60.216.174.131:8083/event/open/api/").append(date).append("/").append(code).append(suf);
resMap.put("src", stringBuffer);
return new ResponseObject(0,"上传成功",resMap);
}
return new ResponseObject(500, "文件不能为空", null);
}catch(Exception e) {
logger.error(e.getMessage(),e);
return new ResponseObject(500, "上传失败", null);
}
}
/**
* @Description 获取文件
* @param path
* @param response
*/
@RequestMapping(value="/open/api/{date}/{path:.+}")
public void fetch(@PathVariable String date, @PathVariable String path, HttpServletResponse response) {
FileInputStream in = null;
OutputStream out = null;
try {
response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/jpeg");
in = new FileInputStream(new File(dir+File.separator+date+File.separator+path));
out = response.getOutputStream();
byte[] buf = new byte[1024 * 1024 * 10];
int len;
while((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
out.flush();
}
out.close();
}catch(Exception e) {
logger.error(e.getMessage(),e);
e.printStackTrace();
}finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}catch(IOException e) {
logger.error(e.getMessage(),e);
e.printStackTrace();
}
}
}