/** * 文件 上传, * /api/uploadimage * @param file * //自定义上传图片的名字为userId.jpg //String fileName = request.getAttribute("userId") + "123456.jpg"; */ @ResponseBody @RequestMapping("/api/uploadimage") public JSONObject uploadimage(HttpServletRequest request)throws Exception { JSONObject result = new JSONObject(); //获取文件需要上传到的路径 String webPath=request.getServletContext().getRealPath(""); String filePath= "/static/xcx_upload/image/"+DateUtil.formatDate(new Date(), "yyyyMMdd")+"/"; FileUtil.makeDirs(webPath+filePath); request.setCharacterEncoding("utf-8"); //设置编码 try { StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request; Iterator<String> iterator = req.getFileNames(); //String fileName = (String) req.getAttribute("bianhao") ; while (iterator.hasNext()) { //拿到所有图片 List<MultipartFile> filelist = req.getFiles(iterator.next()); for(MultipartFile file :filelist ) { // 获取文件名 String fileNames = file.getOriginalFilename(); int split = fileNames.lastIndexOf("."); //获取上传文件的后缀 String extName = fileNames.substring(split + 1, fileNames.length()); //申明UUID String uuid = UUID.randomUUID().toString().replace("-", ""); //组成新的图片名称 String newName = uuid + "." + extName; System.out.println(newName); String destPath = webPath+filePath + newName; //真正写到磁盘上 File file1 = new File(destPath); OutputStream out = new FileOutputStream(file1); out.write(file.getBytes()); out.close(); } } } catch (Exception e) { } return result; }
public List<String> receiveFileToDir(List<MultipartFile> multipartFiles) { // 输出的文件流保存到本地文件 // uploadDir 是设置好的文件保存地址,可自行设置 String path = uploadDir; // 判断文件保存目录是否存在,不存在则创建相关目录 File tempFile = new File(path); if (!tempFile.exists()) { tempFile.mkdirs(); } List<String> fileNameList = new ArrayList<>(); for (MultipartFile file : multipartFiles){ OutputStream os = null; InputStream inputStream = null; String originalFilename = file.getOriginalFilename(); String[] split = originalFilename.split("\\."); String fileName = codeUtilBuil() + "." + split[1]; try { inputStream = file.getInputStream(); } catch (IOException e) { e.printStackTrace(); } // File.separato 系统默认分隔符,相当于 / try { os = new FileOutputStream(tempFile.getPath()+ "/" + File.separator + fileName); // 开始读取 byte[] bs = new byte[1024]; // 读取数据 int length; while ((length = inputStream.read(bs)) != -1) { os.write(bs, 0, length); } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭所有链接 try { os.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } fileNameList.add(path + "/" +fileName); } return fileNameList; }
站长微信:xiaomao0055
站长QQ:14496453