FileUploadController.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. package com.yihu.wlyy.web.common;
  2. import java.beans.Encoder;
  3. import java.io.*;
  4. import java.text.SimpleDateFormat;
  5. import java.util.*;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import javax.sound.sampled.AudioFileFormat;
  9. import javax.sound.sampled.AudioFormat;
  10. import javax.sound.sampled.AudioInputStream;
  11. import javax.sound.sampled.AudioSystem;
  12. import com.fasterxml.jackson.databind.node.ObjectNode;
  13. import com.yihu.wlyy.util.CommonUtil;
  14. import com.yihu.wlyy.util.fastdfs.FastDFSUtil;
  15. import io.swagger.annotations.Api;
  16. import io.swagger.annotations.ApiParam;
  17. import org.apache.commons.codec.EncoderException;
  18. import org.apache.commons.io.FileUtils;
  19. import org.json.JSONObject;
  20. import org.springframework.beans.factory.annotation.Autowired;
  21. import org.springframework.beans.factory.annotation.Value;
  22. import org.springframework.http.MediaType;
  23. import org.springframework.stereotype.Controller;
  24. import org.springframework.util.FileCopyUtils;
  25. import org.springframework.web.bind.annotation.RequestMapping;
  26. import org.springframework.web.bind.annotation.RequestMethod;
  27. import org.springframework.web.bind.annotation.ResponseBody;
  28. import org.springframework.web.multipart.MultipartFile;
  29. import org.springframework.web.multipart.MultipartHttpServletRequest;
  30. import com.yihu.wlyy.util.DateUtil;
  31. import com.yihu.wlyy.util.ImageCompress;
  32. import com.yihu.wlyy.util.SystemConf;
  33. import com.yihu.wlyy.web.BaseController;
  34. @Controller
  35. @RequestMapping(value = "/upload", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  36. @Api(description = "文件上传")
  37. public class FileUploadController extends BaseController {
  38. @ApiParam
  39. FastDFSUtil fastDFSUtil;
  40. @Autowired
  41. private CommonUtil CommonUtil;
  42. @Value("${fastDFS.fastdfs_file_url}")
  43. private String fastdfs_file_url;
  44. /**
  45. * 患者头像上传
  46. *
  47. * @return
  48. * @throws IOException
  49. * @throws IllegalStateException
  50. */
  51. @RequestMapping(value = "patientPhoto", method = RequestMethod.POST/* , headers = "Accept=image/png" */)
  52. @ResponseBody
  53. public String patientPhoto(HttpServletRequest request, HttpServletResponse response, String photo) {
  54. try {
  55. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  56. Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
  57. String fileName = null;
  58. String firstPhoto = null;
  59. for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
  60. // 上传文件
  61. MultipartFile mf = entity.getValue();
  62. fileName = mf.getOriginalFilename();
  63. String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
  64. // 重命名文件
  65. firstPhoto = photo.substring(0, photo.lastIndexOf(".")) + "_small." + fileExt;
  66. File uploadFile = new File(SystemConf.getInstance().getTempPath() + File.separator + firstPhoto);
  67. // 拷贝文件流到指定文件路径
  68. FileCopyUtils.copy(mf.getBytes(), uploadFile);
  69. }
  70. JSONObject json = new JSONObject();
  71. json.put("status", 200);
  72. json.put("msg", "上传成功");
  73. // 图片标识对象的HTTP链接
  74. json.put("urls", String.join(",", firstPhoto));
  75. System.out.println("图片上传:" + json.toString());
  76. return json.toString();
  77. } catch (Exception e) {
  78. error(e);
  79. return error(-1, "上传失败");
  80. }
  81. }
  82. /**
  83. * 图片上传
  84. *
  85. * @return
  86. * @throws IOException
  87. * @throws IllegalStateException
  88. */
  89. @RequestMapping(value = "image", method = RequestMethod.POST/* , headers = "Accept=image/png" */)
  90. @ResponseBody
  91. public String image(HttpServletRequest request, HttpServletResponse response) {
  92. // 圖片列表
  93. List<File> images = new ArrayList<File>();
  94. List<String> tempPaths = new ArrayList<String>();
  95. // 文件保存的临时路径
  96. String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
  97. // 拼接年月日路径
  98. String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
  99. try {
  100. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  101. Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
  102. // 创建文件夹
  103. File file = new File(tempPath + datePath);
  104. if (!file.exists()) {
  105. file.mkdirs();
  106. }
  107. String fileName = null;
  108. for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
  109. // 上传文件
  110. MultipartFile mf = entity.getValue();
  111. fileName = mf.getOriginalFilename();
  112. String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
  113. // 重命名文件
  114. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
  115. String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
  116. File uploadFile = new File(tempPath + datePath + newFileName);
  117. // 拷贝文件流到指定文件路径
  118. FileCopyUtils.copy(mf.getBytes(), uploadFile);
  119. // 生成缩略图
  120. ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
  121. // 添加到上传成功数组中
  122. images.add(uploadFile);
  123. tempPaths.add(datePath + newFileName);
  124. }
  125. String urls = "";
  126. for (String image : tempPaths) {
  127. if (urls.length() == 0) {
  128. urls = image;
  129. } else {
  130. urls += "," + image;
  131. }
  132. }
  133. JSONObject json = new JSONObject();
  134. json.put("status", 200);
  135. json.put("msg", "上传成功");
  136. // 图片标识对象的HTTP链接
  137. json.put("urls", urls);
  138. System.out.println("图片上传:" + json.toString());
  139. return json.toString();
  140. } catch (Exception e) {
  141. error(e);
  142. try {
  143. // 清除垃圾图片
  144. for (File file : images) {
  145. FileUtils.forceDelete(file);
  146. }
  147. } catch (Exception e2) {
  148. error(e2);
  149. }
  150. return error(-1, "上传失败");
  151. }
  152. }
  153. /**
  154. * 聊天附件上传
  155. *
  156. * @return
  157. * @throws IOException
  158. * @throws IllegalStateException
  159. */
  160. @RequestMapping(value = "chat", method = RequestMethod.POST)
  161. @ResponseBody
  162. public String chatFile(HttpServletRequest request, HttpServletResponse response) {
  163. List<String> tempPaths = new ArrayList<String>();
  164. try {
  165. String fastUrl = fastdfs_file_url;
  166. String type = request.getParameter("type");
  167. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  168. Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
  169. String fileName = null;
  170. for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
  171. // 上传文件
  172. MultipartFile mf = entity.getValue();
  173. fileName = mf.getOriginalFilename();
  174. if("3".equals(type)){
  175. String tempPath = CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
  176. String map3Path = tempPath.substring(0,tempPath.lastIndexOf("."));
  177. CommonUtil.changeToMp3(tempPath,map3Path);
  178. File tempFile = new File(tempPath);
  179. File mp3File = new File(map3Path);
  180. ObjectNode objectNode = fastDFSUtil.upload(new FileInputStream(mp3File),"mp3","");
  181. tempPaths.add(fastUrl + objectNode.get("groupName").toString().replaceAll("\"","")
  182. + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
  183. if(tempFile!=null){
  184. tempFile.delete();
  185. }
  186. if(mp3File!=null){
  187. mp3File.delete();
  188. }
  189. }else if("4".equals(type)){
  190. String tempPath = CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
  191. String pngPath = tempPath.substring(0,tempPath.lastIndexOf("."))+".png";
  192. File tempFile = new File(tempPath);
  193. File pngFile = new File(pngPath);
  194. long times = CommonUtil.getVideoTimeAndImg(tempPath,pngPath);
  195. if(times<1000){
  196. JSONObject json = new JSONObject();
  197. json.put("status", -1);
  198. json.put("success",true);
  199. json.put("msg", "视频录制时间太短!");
  200. json.put("times", times);
  201. return json.toString();
  202. }
  203. ObjectNode imgNode = fastDFSUtil.upload(new FileInputStream(pngPath),"png","");
  204. String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
  205. ObjectNode videoNode = fastDFSUtil.upload(new FileInputStream(tempPath),fileExt,"");
  206. tempPaths.add(fastUrl + imgNode.get("groupName").toString().replaceAll("\"","")
  207. + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
  208. tempPaths.add(fastUrl + videoNode.get("groupName").toString().replaceAll("\"","")
  209. + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
  210. tempPaths.add(times+"");
  211. if(tempFile!=null){
  212. tempFile.delete();
  213. }
  214. if(pngFile!=null){
  215. pngFile.delete();
  216. }
  217. } else{
  218. String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
  219. ObjectNode objectNode = fastDFSUtil.upload(mf.getInputStream() ,fileExt,"");
  220. tempPaths.add(fastUrl + objectNode.get("groupName").toString().replaceAll("\"","")
  221. + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
  222. }
  223. }
  224. String urls = String.join(",", tempPaths);
  225. JSONObject json = new JSONObject();
  226. json.put("status", 200);
  227. json.put("success",true);
  228. json.put("msg", "上传成功");
  229. // 图片标识对象的HTTP链接
  230. json.put("urls", urls);
  231. System.out.println("附件上传:" + json.toString());
  232. return json.toString();
  233. } catch (Exception e) {
  234. error(e);
  235. return error(-1, "上传失败");
  236. }
  237. }
  238. /**
  239. * 语音上传
  240. *
  241. * @param request
  242. * @param response
  243. * @return
  244. */
  245. @RequestMapping(value = "voice", method = RequestMethod.POST)
  246. @ResponseBody
  247. public String voice(HttpServletRequest request, HttpServletResponse response) {
  248. // 圖片列表
  249. List<File> voices = new ArrayList<File>();
  250. List<String> tempPaths = new ArrayList<String>();
  251. // 文件保存的临时路径
  252. String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
  253. // 拼接年月日路径
  254. String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
  255. try {
  256. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  257. Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
  258. // 创建文件夹
  259. File file = new File(tempPath + datePath);
  260. if (!file.exists()) {
  261. file.mkdirs();
  262. }
  263. String fileName = null;
  264. for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
  265. // 上传文件
  266. MultipartFile mf = entity.getValue();
  267. fileName = mf.getOriginalFilename();
  268. String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
  269. // 重命名文件
  270. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
  271. String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
  272. File uploadFile = new File(tempPath + datePath + newFileName);
  273. // 拷贝文件流到指定文件路径
  274. FileCopyUtils.copy(mf.getBytes(), uploadFile);
  275. // 添加到上传成功数组中
  276. voices.add(uploadFile);
  277. tempPaths.add(datePath + newFileName);
  278. }
  279. String urls = "";
  280. for (String voice : tempPaths) {
  281. if (urls.length() == 0) {
  282. urls = voice;
  283. } else {
  284. urls += "," + voice;
  285. }
  286. }
  287. JSONObject json = new JSONObject();
  288. json.put("status", 200);
  289. json.put("msg", "上传成功");
  290. // 图片标识对象的HTTP链接
  291. json.put("urls", urls);
  292. System.out.println("语音上传:" + json.toString());
  293. return json.toString();
  294. } catch (Exception e) {
  295. error(e);
  296. try {
  297. // 清除垃圾图片
  298. for (File file : voices) {
  299. FileUtils.forceDelete(file);
  300. }
  301. } catch (Exception e2) {
  302. error(e2);
  303. }
  304. return error(-1, "上传失败");
  305. }
  306. }
  307. /**
  308. * 语音上传
  309. * @param request
  310. * @param response
  311. * @return
  312. */
  313. @RequestMapping(value = "test", method = RequestMethod.POST)
  314. @ResponseBody
  315. public String test(HttpServletRequest request, HttpServletResponse response) throws Exception {
  316. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  317. Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
  318. List<String> tempPaths = new ArrayList<String>();
  319. String fastUrl = fastdfs_file_url;
  320. for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
  321. MultipartFile mf = entity.getValue();
  322. String fileName = mf.getOriginalFilename();
  323. String tempPath = CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
  324. String pngPath = tempPath.substring(0,tempPath.lastIndexOf("."))+".png";
  325. File tempFile = new File(tempPath);
  326. File pngFile = new File(pngPath);
  327. long times = CommonUtil.getVideoTimeAndImg(tempPath,pngPath);
  328. ObjectNode imgNode = fastDFSUtil.upload(new FileInputStream(pngPath),"png","");
  329. String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
  330. ObjectNode videoNode = fastDFSUtil.upload(new FileInputStream(tempPath),fileExt,"");
  331. tempPaths.add(fastUrl + imgNode.get("groupName").toString().replaceAll("\"","")
  332. + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
  333. tempPaths.add(fastUrl + videoNode.get("groupName").toString().replaceAll("\"","")
  334. + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
  335. tempPaths.add(times+"");
  336. if(tempFile!=null){
  337. tempFile.delete();
  338. }
  339. if(pngFile!=null){
  340. pngFile.delete();
  341. }
  342. }
  343. String urls = String.join(",", tempPaths);
  344. return urls;
  345. }
  346. }