org.springframework.web.multipart.MultipartFile Java Examples
The following examples show how to use
org.springframework.web.multipart.MultipartFile.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PetApiDelegate.java From openapi-generator with Apache License 2.0 | 6 votes |
/** * POST /pet/{petId}/uploadImage : uploads an image * * @param petId ID of pet to update (required) * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) * @return successful operation (status code 200) * @see PetApi#uploadFile */ default Mono<ResponseEntity<ModelApiResponse>> uploadFile(Long petId, String additionalMetadata, MultipartFile file, ServerWebExchange exchange) { Mono<Void> result = Mono.empty(); exchange.getResponse().setStatusCode(HttpStatus.NOT_IMPLEMENTED); for (MediaType mediaType : exchange.getRequest().getHeaders().getAccept()) { if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; result = ApiUtil.getExampleResponse(exchange, exampleString); break; } } return result.then(Mono.empty()); }
Example #2
Source File: OssBootUtil.java From teaching with Apache License 2.0 | 6 votes |
/** * 上传文件至阿里云 OSS * 文件上传成功,返回文件完整访问路径 * 文件上传失败,返回 null * * @param file 待上传文件 * @param fileDir 文件保存目录 * @return oss 中的相对文件路径 */ public static String upload(MultipartFile file, String fileDir) { initOSS(endPoint, accessKeyId, accessKeySecret); StringBuilder fileUrl = new StringBuilder(); try { String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')); String fileName = UUID.randomUUID().toString().replace("-", "") + suffix; if (!fileDir.endsWith("/")) { fileDir = fileDir.concat("/"); } fileUrl = fileUrl.append(fileDir + fileName); if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) { FILE_URL = staticDomain + "/" + fileUrl; } else { FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl; } PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.getInputStream()); // 设置权限(公开读) ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead); if (result != null) { System.out.println("------OSS文件上传成功------" + fileUrl); } } catch (IOException e) { e.printStackTrace(); return null; } return FILE_URL; }
Example #3
Source File: ProductManageController.java From mmall-kay-Java with Apache License 2.0 | 6 votes |
/** * 富文本上传-------富文本上传根据使用的插件,有固定的返回值设置,这里使用Simditor * { * "success": true/false, * "msg": "error message", # optional * "file_path": "[real file path]" * } */ @RequestMapping("richtext_img_upload.do") @ResponseBody public Map richTextUpload(@RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) { Map resultMap = new HashMap(); String path = request.getSession().getServletContext().getRealPath("upload"); String uploadFilePath = iFileService.upload(file, path); if (StringUtils.isBlank(uploadFilePath)) { resultMap.put("success", false); resultMap.put("msg", "上传失败"); return resultMap; } String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + uploadFilePath; resultMap.put("success", true); resultMap.put("msg", "上传成功"); resultMap.put("file_path", url); //插件约定 response.addHeader("Access-Control-Allow-Headers","X-File-Name"); return resultMap; }
Example #4
Source File: BooksServiceImpl.java From springbook with MIT License | 6 votes |
@Override public int update(Bookadmin b,MultipartFile file){ if (file != null){ String originalFilename = file.getOriginalFilename(); String picName = UUID.randomUUID() + originalFilename; File updatePic = new File("C:/Users/finch/IdeaProjects/springbook/src/main/webapp/WEB-INF/static/img/" + picName); try{ file.transferTo(updatePic); b.setPic(picName); } catch (IOException e) { e.printStackTrace(); } } return booksMapper.update(b); }
Example #5
Source File: FileStorageController.java From n2o-framework with Apache License 2.0 | 6 votes |
@Synchronized public FileModel storeFile(MultipartFile file) { try { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); Path targetLocation = path.resolve(fileName); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); targetLocation.toFile().deleteOnExit(); String uri = ServletUriComponentsBuilder.fromPath(fileName).toUriString(); FileModel model = new FileModel("" + (++id), fileName, uri); storage.put("" + id, model); return model; } catch (IOException e) { e.printStackTrace(); return null; } }
Example #6
Source File: DamnYouController.java From biliob_backend with MIT License | 6 votes |
@RequestMapping(method = RequestMethod.POST, value = "/api/damn-you/upload") public ResponseEntity<Result<String>> uploadData( @RequestParam("file") MultipartFile file) throws IOException { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件后缀 assert fileName != null; String prefix = fileName.substring(fileName.lastIndexOf(".")); final File tempFile = File.createTempFile(fileName, prefix); file.transferTo(tempFile); ZipFile zipFile = new ZipFile(tempFile); InputStream inputStream = file.getInputStream(); ZipInputStream zipInputStream = new ZipInputStream(inputStream, Charset.defaultCharset()); damnYouService.deleteFile(tempFile); damnYouService.saveData(zipInputStream, zipFile); return ResponseEntity.accepted().body(new Result<>(ResultEnum.ACCEPTED)); }
Example #7
Source File: FileUploadController.java From charging_pile_cloud with MIT License | 6 votes |
/** * 阿里云上传图片接口 * * @param request * @param response * @return */ @RequestMapping(value = "uploadAliOss", method = RequestMethod.POST) @ResponseBody @ApiOperation(notes = "上传图片", value = "上传图片") public Map<String, Object> uploadAliOss(HttpServletRequest request, HttpServletResponse response) { MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request; MultipartFile file = mhs.getFile("file"); try { String fileName = FileUpload.getFileName(file); if (StringUtils.isBlank(fileName)) { throw new CommonException("未知的文件格式"); } String url = OSSInterface.uploadImage(file.getOriginalFilename(), file.getInputStream(), OSSFather.bucketName_user); if(com.util.StringUtils.isBlank(url)){ return ResponseUtil.getNotNormalMap(ResponseMsg.UPLOAD_FAIL); }else { return ResponseUtil.getSuccessNoMsg(url); } } catch (IOException e) { throw new CommonException("图片上传失败"); } }
Example #8
Source File: FileUtils.java From sk-admin with Apache License 2.0 | 6 votes |
/** * 将文件名解析成文件的上传路径 */ public static File upload(MultipartFile file, String filePath) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS"); String name = getFileNameNoEx(file.getOriginalFilename()); String suffix = getExtensionName(file.getOriginalFilename()); String nowStr = "-" + format.format(date); try { String fileName = name + nowStr + "." + suffix; String path = filePath + fileName; // getCanonicalFile 可解析正确各种路径 File dest = new File(path).getCanonicalFile(); // 检测是否存在目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } // 文件写入 file.transferTo(dest); return dest; } catch (Exception e) { e.printStackTrace(); } return null; }
Example #9
Source File: TableService.java From DBus with Apache License 2.0 | 6 votes |
public ResultEntity importRulesByTableId(Integer tableId, MultipartFile uploadFile) throws Exception { File saveDir = new File(SystemUtils.getJavaIoTmpDir(), String.valueOf(System.currentTimeMillis())); if (!saveDir.exists()) saveDir.mkdirs(); File tempFile = new File(saveDir, uploadFile.getOriginalFilename()); uploadFile.transferTo(tempFile); StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(tempFile)); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } } finally { if (br != null) { br.close(); } if (tempFile != null && tempFile.exists()) { tempFile.delete(); } } return sender.post(ServiceNames.KEEPER_SERVICE, "/tables/importRulesByTableId/" + tableId, sb.toString()).getBody(); }
Example #10
Source File: FileService.java From flash-waimai with MIT License | 6 votes |
/** * 文件上传 * @param multipartFile * @return */ public FileInfo upload(MultipartFile multipartFile){ String uuid = UUID.randomUUID().toString(); String realFileName = uuid +"."+ multipartFile.getOriginalFilename().split("\\.")[1]; try { File file = new File(configCache.get(ConfigKeyEnum.SYSTEM_FILE_UPLOAD_PATH.getValue()) + File.separator+realFileName); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } multipartFile.transferTo(file); return save(multipartFile.getOriginalFilename(),file); } catch (Exception e) { e.printStackTrace(); return null; } }
Example #11
Source File: SysRoleServiceImpl.java From jeecg-boot with Apache License 2.0 | 5 votes |
@Override public Result importExcelCheckRoleCode(MultipartFile file, ImportParams params) throws Exception { List<Object> listSysRoles = ExcelImportUtil.importExcel(file.getInputStream(), SysRole.class, params); int totalCount = listSysRoles.size(); List<String> errorStrs = new ArrayList<>(); // 去除 listSysRoles 中重复的数据 for (int i = 0; i < listSysRoles.size(); i++) { String roleCodeI =((SysRole)listSysRoles.get(i)).getRoleCode(); for (int j = i + 1; j < listSysRoles.size(); j++) { String roleCodeJ =((SysRole)listSysRoles.get(j)).getRoleCode(); // 发现重复数据 if (roleCodeI.equals(roleCodeJ)) { errorStrs.add("第 " + (j + 1) + " 行的 roleCode 值:" + roleCodeI + " 已存在,忽略导入"); listSysRoles.remove(j); break; } } } // 去掉 sql 中的重复数据 Integer errorLines=0; Integer successLines=0; List<String> list = ImportExcelUtil.importDateSave(listSysRoles, ISysRoleService.class, errorStrs, CommonConstant.SQL_INDEX_UNIQ_SYS_ROLE_CODE); errorLines+=list.size(); successLines+=(listSysRoles.size()-errorLines); return ImportExcelUtil.imporReturnRes(errorLines,successLines,list); }
Example #12
Source File: FileUploadController.java From springboot-learning-experience with Apache License 2.0 | 5 votes |
@PostMapping("/upload1") @ResponseBody public Map<String, String> upload1(@RequestParam("file") MultipartFile file) throws IOException { log.info("[文件类型] - [{}]", file.getContentType()); log.info("[文件名称] - [{}]", file.getOriginalFilename()); log.info("[文件大小] - [{}]", file.getSize()); // TODO 将文件写入到指定目录(具体开发中有可能是将文件写入到云存储/或者指定目录通过 Nginx 进行 gzip 压缩和反向代理,此处只是为了演示故将地址写成本地电脑指定目录) file.transferTo(new File("/Users/Winterchen/Desktop/javatest" + file.getOriginalFilename())); Map<String, String> result = new HashMap<>(16); result.put("contentType", file.getContentType()); result.put("fileName", file.getOriginalFilename()); result.put("fileSize", file.getSize() + ""); return result; }
Example #13
Source File: RelatedContentResource.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/rest/content/raw/text", method = RequestMethod.POST) public String createTemporaryRawRelatedContentText(@RequestParam("file") MultipartFile file) { RelatedContentRepresentation relatedContentRepresentation = super.createTemporaryRawRelatedContent(file); String relatedContentJson = null; try { relatedContentJson = objectMapper.writeValueAsString(relatedContentRepresentation); } catch (Exception e) { logger.error("Error while processing RelatedContent representation json", e); throw new InternalServerErrorException("Related Content could not be saved"); } return relatedContentJson; }
Example #14
Source File: FileService.java From WeEvent with Apache License 2.0 | 5 votes |
private UploadChunkParam parseUploadChunkRequest(HttpServletRequest request) throws GovernanceException { UploadChunkParam chunkParam = new UploadChunkParam(); String fileId = request.getParameter("identifier"); FileChunksMeta fileChunksMeta = this.fileChunksMap.get(fileId).getKey(); chunkParam.setFileChunksMeta(fileChunksMeta); chunkParam.setBrokerId(Integer.parseInt(request.getParameter("brokerId"))); chunkParam.setChunkNumber(Integer.parseInt(request.getParameter("chunkNumber")) - 1); chunkParam.setFileId(fileId); CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); if (!Objects.isNull(file)) { try { chunkParam.setChunkData(file.getBytes()); } catch (IOException e) { log.error("parse upload chunk data error.", e); throw new GovernanceException(ErrorCode.PARSE_CHUNK_REQUEST_ERROR); } } } } return chunkParam; }
Example #15
Source File: ByteArrayMultipartFileEditorTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void setValueAsMultipartFile() throws Exception { String expectedValue = "That is comforting to know"; MultipartFile file = mock(MultipartFile.class); given(file.getBytes()).willReturn(expectedValue.getBytes()); editor.setValue(file); assertEquals(expectedValue, editor.getAsText()); }
Example #16
Source File: UploadFileController.java From NetworkDisk_Storage with GNU General Public License v2.0 | 5 votes |
/** * 上传文件(内部调用) * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "upload", method = RequestMethod.POST) public RestAPIResult<String> upload(MultipartFile file) throws IOException { logger.info("上传文件(内部调用)请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("上传文件(内部调用)数据处理开始"); RestAPIResult<String> result = uploadFileProvider.uploadHandle(file); logger.info("上传文件(内部调用)数据处理结束,result:{}", result); stopWatch.stop(); logger.info("上传文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; }
Example #17
Source File: WebDataBinder.java From spring-analysis-note with MIT License | 5 votes |
/** * Bind all multipart files contained in the given request, if any * (in case of a multipart request). To be called by subclasses. * <p>Multipart files will only be added to the property values if they * are not empty or if we're configured to bind empty multipart files too. * @param multipartFiles a Map of field name String to MultipartFile object * @param mpvs the property values to be bound (can be modified) * @see org.springframework.web.multipart.MultipartFile * @see #setBindEmptyMultipartFiles */ protected void bindMultipart(Map<String, List<MultipartFile>> multipartFiles, MutablePropertyValues mpvs) { multipartFiles.forEach((key, values) -> { if (values.size() == 1) { MultipartFile value = values.get(0); if (isBindEmptyMultipartFiles() || !value.isEmpty()) { mpvs.add(key, value); } } else { mpvs.add(key, values); } }); }
Example #18
Source File: BulkUploadTest.java From Insights with Apache License 2.0 | 5 votes |
@Test(priority = 3) public void testUploadDataWithVariedEpochTimesInDatabase() throws InsightsCustomException, IOException { FileInputStream input = new FileInputStream(fileWithVariedEpochTimes); MultipartFile multipartFile = new MockMultipartFile("file", fileWithVariedEpochTimes.getName(), "text/plain", IOUtils.toByteArray(input)); boolean response = bulkUploadService.uploadDataInDatabase(multipartFile, bulkUploadTestData.toolName, bulkUploadTestData.label, bulkUploadTestData.insightTimeField, bulkUploadTestData.nullInsightTimeFormat); Assert.assertEquals(response, true); Assert.assertFalse(multipartFile.isEmpty()); Assert.assertTrue(multipartFile.getSize() < filesizeMaxValue); }
Example #19
Source File: RequestPartServletServerHttpRequestTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void getContentType() throws Exception { MultipartFile part = new MockMultipartFile("part", "", "application/json", "content".getBytes("UTF-8")); this.mockRequest.addFile(part); ServerHttpRequest request = new RequestPartServletServerHttpRequest(this.mockRequest, "part"); HttpHeaders headers = request.getHeaders(); assertNotNull(headers); assertEquals(MediaType.APPLICATION_JSON, headers.getContentType()); }
Example #20
Source File: FsServiceImpl.java From super-cloudops with Apache License 2.0 | 5 votes |
@Override public String uploadFile(MultipartFile file) { Date now = new Date(); String fileName = file.getOriginalFilename();// 文件名 String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名 fileName = UUID.randomUUID() + suffixName;// 新文件名 fileName = "/" + DateUtils2.formatDate(now, "yyyyMMddHHmmss") + "/" + fileName;// 加一级日期目录 String path = fsProperties.getBaseFilePath() + fileName; saveFile(file, path); return fsProperties.getBaseFileUrl() + fileName; }
Example #21
Source File: MultipartController.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@RequestMapping( value = "api/v1/multipart", method = RequestMethod.PUT, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public UploadFileResponse uploadFileWithPut(@RequestParam("file") MultipartFile file) { return new UploadFileResponse(file.getOriginalFilename(), file.getContentType(), file.getSize()); }
Example #22
Source File: UploadServiceImpl.java From NoteBlog with MIT License | 5 votes |
@Override public Map<String, Object> uploadAvatar(MultipartFile avatar, String username) { String path = FileType.IMAGE; String fileName = avatar.getOriginalFilename(); //扩展名,包括点符号 String ext = fileName.substring(fileName.lastIndexOf(".")); fileName = LangUtils.random.uuidCool().concat(ext); try { File targetFile = new File(path); boolean m = true; if (!targetFile.exists()) { m = targetFile.mkdirs(); } if (m) { String filePath = saveFile(path, fileName, avatar::getBytes); String virtualPath = "/upload" + path + "/" + fileName; uploadRepository.save(Upload.builder().diskPath(filePath).virtualPath(virtualPath).type(avatar.getContentType()).upload(now()).build()); int uploadAvatar = userRepository.updateAdminAvatar(virtualPath, username); assert uploadAvatar == 1; return LayUpload.ok("上传头像成功,重新登陆后生效!", virtualPath); } else { return LayUpload.err("文件创建失败!"); } } catch (IOException e) { log.error("文件IO出错,出错信息:{}", e.getLocalizedMessage()); return LayUpload.err("文件IO出错,出错信息:" + e.getLocalizedMessage()); } catch (Exception e) { return LayUpload.err("上传出错,出错信息:" + e.getLocalizedMessage()); } }
Example #23
Source File: RequestPartIntegrationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/test", method = POST, consumes = {"multipart/mixed", "multipart/form-data"}) public ResponseEntity<Object> create(@RequestPart(name = "json-data") TestData testData, @RequestPart("file-data") Optional<MultipartFile> file, @RequestPart(name = "empty-data", required = false) TestData emptyData, @RequestPart(name = "iso-8859-1-data") byte[] iso88591Data) { Assert.assertArrayEquals(new byte[]{(byte) 0xC4}, iso88591Data); String url = "http://localhost:8080/test/" + testData.getName() + "/" + file.get().getOriginalFilename(); HttpHeaders headers = new HttpHeaders(); headers.setLocation(URI.create(url)); return new ResponseEntity<Object>(headers, HttpStatus.CREATED); }
Example #24
Source File: RelatedContentResource.java From flowable-engine with Apache License 2.0 | 5 votes |
@PostMapping(value = "/rest/tasks/{taskId}/raw-content/text") public String createContentItemOnTaskText(@PathVariable("taskId") String taskId, @RequestParam("file") MultipartFile file) { ContentItemRepresentation contentItem = super.createContentItemOnTask(taskId, file); String contentItemJson = null; try { contentItemJson = objectMapper.writeValueAsString(contentItem); } catch (Exception e) { LOGGER.error("Error while processing ContentItem representation json", e); throw new InternalServerErrorException("ContentItem on task could not be saved"); } return contentItemJson; }
Example #25
Source File: UserController.java From LuckyFrameWeb with GNU Affero General Public License v3.0 | 5 votes |
@Log(title = "用户管理", businessType = BusinessType.IMPORT) @RequiresPermissions("system:user:import") @PostMapping("/importData") @ResponseBody public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { ExcelUtil<User> util = new ExcelUtil<>(User.class); List<User> userList = util.importExcel(file.getInputStream()); String message = userService.importUser(userList, updateSupport); return AjaxResult.success(message); }
Example #26
Source File: ImageUploadService.java From zhcet-web with Apache License 2.0 | 5 votes |
public Avatar upload(UserAuth user, String name, MultipartFile file) throws ExecutionException, InterruptedException { // Normalize (Crop) Image in parallel CompletableFuture<Image> avatarFuture = imageEditService.normalizeAsync(file, ORIGINAL_AVATAR_SIZE); CompletableFuture<Image> avatarThumbnailFuture = imageEditService.normalizeAsync(file, AVATAR_SIZE); CompletableFuture.allOf(avatarFuture, avatarThumbnailFuture).join(); // Prepare Images to be saved Image avatarImage = avatarFuture.get(); Image avatarThumbnail = avatarThumbnailFuture.get(); avatarImage.setName(name); avatarThumbnail.setName(name + "_thumb"); avatarThumbnail.setThumbnail(true); // Generate Avatar and send images for upload Avatar avatar = new Avatar(); UploadedImage uploadedAvatar = uploadImage(avatarImage); avatar.setAvatar(uploadedAvatar.getUrl()); UploadedImage uploadedThumbnail = uploadImage(avatarImage); uploadedThumbnail.setThumbnail(true); avatar.setThumbnail(uploadedThumbnail.getUrl()); uploadToCloud(user, avatarImage, uploadedAvatar); uploadToCloud(user, avatarThumbnail, uploadedThumbnail); return avatar; }
Example #27
Source File: WebuiImageService.java From metasfresh-webui-api-legacy with GNU General Public License v3.0 | 5 votes |
public WebuiImageId uploadImage(final MultipartFile file) throws IOException { final String name = file.getOriginalFilename(); final byte[] data = file.getBytes(); final String contentType = file.getContentType(); final String filenameNorm = normalizeUploadFilename(name, contentType); final MImage adImage = new MImage(Env.getCtx(), 0, ITrx.TRXNAME_None); adImage.setName(filenameNorm); adImage.setBinaryData(data); // TODO: introduce adImage.setTemporary(true); InterfaceWrapperHelper.save(adImage); return WebuiImageId.ofRepoId(adImage.getAD_Image_ID()); }
Example #28
Source File: FastDfsAutoConfigure.java From zuihou-admin-boot with Apache License 2.0 | 5 votes |
@Override protected void uploadFile(File file, MultipartFile multipartFile) throws Exception { StorePath storePath = storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), file.getExt(), null); file.setUrl(fileProperties.getUriPrefix() + storePath.getFullPath()); file.setGroup(storePath.getGroup()); file.setPath(storePath.getPath()); }
Example #29
Source File: QiniuCloudService.java From my-site with Apache License 2.0 | 5 votes |
public String upload(MultipartFile file, String fileName) { //构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(Zone.zone0()); //...其他参数参考类注释 UploadManager uploadManager = new UploadManager(cfg); //默认不指定key的情况下,以文件内容的hash值作为文件名 String key = null; Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); String upToken = auth.uploadToken(BUCKET); try { Response response = null; response = uploadManager.put(file.getInputStream(), fileName, upToken, null, null); //解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); System.out.println(putRet.key); System.out.println(putRet.hash); return putRet.key; } catch (QiniuException ex) { Response r = ex.response; System.err.println(r.toString()); try { System.err.println(r.bodyString()); } catch (QiniuException ex2) { //ignore } } catch (IOException e) { e.printStackTrace(); } return null; }
Example #30
Source File: UploadController.java From tianti with Apache License 2.0 | 5 votes |
@RequestMapping("/uploadAttach") public void uploadAttach(HttpServletRequest request, PrintWriter out) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); MultipartFile multipartFile = null; String fileName = null; for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) { multipartFile = set.getValue();// 文件名 } fileName = this.storeIOc(multipartRequest, multipartFile); out.print(fileName); }