Java Code Examples for org.springframework.web.multipart.MultipartFile

The following examples show how to use org.springframework.web.multipart.MultipartFile. These examples are extracted from open source projects. 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 Project: teaching   Source File: OssBootUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 上传文件至阿里云 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 2
Source Project: flash-waimai   Source File: FileService.java    License: MIT License 6 votes vote down vote up
/**
 * 文件上传
 * @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 3
Source Project: charging_pile_cloud   Source File: FileUploadController.java    License: MIT License 6 votes vote down vote up
/**
 * 阿里云上传图片接口
 *
 * @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 4
Source Project: DBus   Source File: TableService.java    License: Apache License 2.0 6 votes vote down vote up
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 5
Source Project: sk-admin   Source File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将文件名解析成文件的上传路径
 */
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 6
Source Project: springbook   Source File: BooksServiceImpl.java    License: MIT License 6 votes vote down vote up
@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 7
Source Project: mmall-kay-Java   Source File: ProductManageController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 富文本上传-------富文本上传根据使用的插件,有固定的返回值设置,这里使用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 8
Source Project: biliob_backend   Source File: DamnYouController.java    License: MIT License 6 votes vote down vote up
@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 9
Source Project: n2o-framework   Source File: FileStorageController.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: openapi-generator   Source File: PetApiDelegate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 11
public void handle(
		@RequestParam Map<String, String> param1,
		@RequestParam MultiValueMap<String, String> param2,
		@RequestParam Map<String, MultipartFile> param3,
		@RequestParam MultiValueMap<String, MultipartFile> param4,
		@RequestParam Map<String, Part> param5,
		@RequestParam MultiValueMap<String, Part> param6,
		@RequestParam("name") Map<String, String> param7,
		Map<String, String> param8) {
}
 
Example 12
Source Project: DBus   Source File: JarManagerController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping("/uploads/{version}/{type}/{category}")
public ResultEntity uploads(@PathVariable String version,
                            @PathVariable String type,
                            @PathVariable String category,
                            @RequestParam MultipartFile jarFile) throws Exception {
    return service.uploads(category, version, type, jarFile);
}
 
Example 13
/**
 * 上传文件(内部调用)
 *
 * @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 14
Source Project: spring-analysis-note   Source File: WebDataBinder.java    License: MIT License 5 votes vote down vote up
/**
 * 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 15
@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
@Test  // SPR-13319
public void filenameRfc5987() throws Exception {
	String disposition = "form-data; name=\"file\"; filename*=\"UTF-8''foo-%c3%a4-%e2%82%ac.html\"";
	StandardMultipartHttpServletRequest request = requestWithPart("file", disposition, "");

	MultipartFile multipartFile = request.getFile("file");
	assertNotNull(multipartFile);
	assertEquals("foo-ä-€.html", multipartFile.getOriginalFilename());
}
 
Example 17
Source Project: my-site   Source File: AttAchController.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation("markdown文件上传")
@PostMapping("/uploadfile")
public void fileUpLoadToTencentCloud(HttpServletRequest request,
                                            HttpServletResponse response,
                                            @ApiParam(name = "editormd-image-file", value = "文件数组", required = true)
                                            @RequestParam(name = "editormd-image-file", required = true)
                                            MultipartFile file){
    //文件上传
    try {
        request.setCharacterEncoding( "utf-8" );
        response.setHeader( "Content-Type" , "text/html" );

        String fileName = TaleUtils.getFileKey(file.getOriginalFilename()).replaceFirst("/","");

        qiniuCloudService.upload(file, fileName);
        AttAchDomain attAch = new AttAchDomain();
        HttpSession session = request.getSession();
        UserDomain sessionUser = (UserDomain) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        attAch.setAuthorId(sessionUser.getUid());
        attAch.setFtype(TaleUtils.isImage(file.getInputStream()) ? Types.IMAGE.getType() : Types.FILE.getType());
        attAch.setFname(fileName);
        attAch.setFkey(qiniuCloudService.QINIU_UPLOAD_SITE + fileName);
        attAchService.addAttAch(attAch);
        response.getWriter().write( "{\"success\": 1, \"message\":\"上传成功\",\"url\":\"" + attAch.getFkey() + "\"}" );
    } catch (IOException e) {
        e.printStackTrace();
        try {
            response.getWriter().write( "{\"success\":0}" );
        } catch (IOException e1) {
            throw BusinessException.withErrorCode(ErrorConstant.Att.UPLOAD_FILE_FAIL)
                    .withErrorMessageArguments(e.getMessage());
        }
        throw BusinessException.withErrorCode(ErrorConstant.Att.UPLOAD_FILE_FAIL)
                .withErrorMessageArguments(e.getMessage());
    }
}
 
Example 18
@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 19
Source Project: jeecg-boot   Source File: SysRoleServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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 20
Source Project: super-cloudops   Source File: FsServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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
@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 22
@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 23
@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 24
Source Project: zhcet-web   Source File: ImageUploadService.java    License: Apache License 2.0 5 votes vote down vote up
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 25
Source Project: zuihou-admin-boot   Source File: FastDfsAutoConfigure.java    License: Apache License 2.0 5 votes vote down vote up
@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 26
Source Project: my-site   Source File: QiniuCloudService.java    License: Apache License 2.0 5 votes vote down vote up
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 27
Source Project: tianti   Source File: UploadController.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 28
Source Project: NoteBlog   Source File: UploadServiceImpl.java    License: MIT License 5 votes vote down vote up
@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 29
Source Project: activiti6-boot2   Source File: RelatedContentResource.java    License: Apache License 2.0 5 votes vote down vote up
@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 30
Source Project: WeEvent   Source File: FileService.java    License: Apache License 2.0 5 votes vote down vote up
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;
}