Java Code Examples for org.springframework.web.multipart.MultipartFile#getOriginalFilename()

The following examples show how to use org.springframework.web.multipart.MultipartFile#getOriginalFilename() . 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: DatabaseController.java    From eladmin with Apache License 2.0 8 votes vote down vote up
@Log("执行SQL脚本")
@ApiOperation(value = "执行SQL脚本")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> upload(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
	String id = request.getParameter("id");
	DatabaseDto database = databaseService.findById(id);
	String fileName;
	if(database != null){
		fileName = file.getOriginalFilename();
		File executeFile = new File(fileSavePath+fileName);
		FileUtil.del(executeFile);
		file.transferTo(executeFile);
		String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile);
		return new ResponseEntity<>(result,HttpStatus.OK);
	}else{
		throw new BadRequestException("Database not exist");
	}
}
 
Example 2
Source File: FastDfsClientUtil.java    From DrivingAgency with MIT License 6 votes vote down vote up
public static String saveFile(MultipartFile multipartFile) throws IOException {
    String[] fileAbsolutePath={};
    String fileName=multipartFile.getOriginalFilename();
    String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
    byte[] file_buff = null;
    InputStream inputStream=multipartFile.getInputStream();
    if(inputStream!=null){
        int len1 = inputStream.available();
        file_buff = new byte[len1];
        inputStream.read(file_buff);
    }
    inputStream.close();
    FastDfsFile file = new FastDfsFile(fileName, file_buff, ext);
    try {
        fileAbsolutePath = FastDfsClientUtil.upload(file);  //upload to fastdfs
    } catch (Exception e) {
        log.error("upload file Exception!",e);
    }
    if (fileAbsolutePath==null) {
        log.error("upload file failed,please upload again!");
    }
    String path= FastDfsClientUtil.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
    return path;
}
 
Example 3
Source File: FlowableDeploymentController.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 部署流程资源
 * 加载ZIP文件中的流程
 */
@PostMapping(value = "/deploy")
@ApiOperation("上传流程定义文件并部署流程")
@Authorize(action = "deploy")
public ResponseMessage<Deployment> deploy(@RequestPart(value = "file") MultipartFile file) throws IOException {
    // 获取上传的文件名
    String fileName = file.getOriginalFilename();

    // 得到输入流(字节流)对象
    InputStream fileInputStream = file.getInputStream();

    // 文件的扩展名
    String extension = FilenameUtils.getExtension(fileName);

    // zip或者bar类型的文件用ZipInputStream方式部署
    DeploymentBuilder deployment = repositoryService.createDeployment();
    if ("zip".equals(extension) || "bar".equals(extension)) {
        ZipInputStream zip = new ZipInputStream(fileInputStream);
        deployment.addZipInputStream(zip);
    } else {
        // 其他类型的文件直接部署
        deployment.addInputStream(fileName, fileInputStream);
    }
    Deployment result = deployment.deploy();

    return ResponseMessage.ok(result);
}
 
Example 4
Source File: FsServiceImpl.java    From super-cloudops with 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 5
Source File: MultipartController.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@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 6
Source File: StorageController.java    From runscore with Apache License 2.0 5 votes vote down vote up
@PostMapping("/uploadPic")
@ResponseBody
public Result uploadPic(@RequestParam("file_data") MultipartFile[] files) throws IOException {
	if (ArrayUtil.isEmpty(files)) {
		return Result.fail("请选择要上传的图片");
	}
	List<String> storageIds = new ArrayList<>();
	for (MultipartFile file : files) {
		String filename = file.getOriginalFilename();
		String storageId = storageService.uploadGatheringCode(file.getInputStream(), file.getSize(),
				file.getContentType(), filename);
		storageIds.add(storageId);
	}
	return Result.success().setData(storageIds);
}
 
Example 7
Source File: MinioController.java    From mall with Apache License 2.0 5 votes vote down vote up
@ApiOperation("文件上传")
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public CommonResult upload(@RequestParam("file") MultipartFile file) {
    try {
        //创建一个MinIO的Java客户端
        MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
        boolean isExist = minioClient.bucketExists(BUCKET_NAME);
        if (isExist) {
            LOGGER.info("存储桶已经存在!");
        } else {
            //创建存储桶并设置只读权限
            minioClient.makeBucket(BUCKET_NAME);
            minioClient.setBucketPolicy(BUCKET_NAME, "*.*", PolicyType.READ_ONLY);
        }
        String filename = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // 设置存储对象名称
        String objectName = sdf.format(new Date()) + "/" + filename;
        // 使用putObject上传一个文件到存储桶中
        minioClient.putObject(BUCKET_NAME, objectName, file.getInputStream(), file.getContentType());
        LOGGER.info("文件上传成功!");
        MinioUploadDto minioUploadDto = new MinioUploadDto();
        minioUploadDto.setName(filename);
        minioUploadDto.setUrl(ENDPOINT + "/" + BUCKET_NAME + "/" + objectName);
        return CommonResult.success(minioUploadDto);
    } catch (Exception e) {
        LOGGER.info("上传发生错误: {}!", e.getMessage());
    }
    return CommonResult.failed();
}
 
Example 8
Source File: ValidFeignClientTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, path = "/multipartPojo",
		consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
		produces = MediaType.TEXT_PLAIN_VALUE)
String multipartPojo(@RequestPart("hello") String hello,
		@RequestPart("world") String world, @RequestPart("pojo1") Hello pojo1,
		@RequestPart("pojo2") Hello pojo2,
		@RequestPart("file") MultipartFile file) {
	return hello + world + pojo1.getMessage() + pojo2.getMessage()
			+ file.getOriginalFilename();
}
 
Example 9
Source File: ControllerUtils.java    From sample-boot-micro with MIT License 5 votes vote down vote up
/**
 * ファイルアップロード情報(MultipartFile)をReportFileへ変換します。
 * <p>acceptExtensionsに許容するファイル拡張子(小文字統一)を設定してください。
 */
public static ReportFile uploadFile(final MultipartFile file, final String... acceptExtensions) {
    String fname = StringUtils.lowerCase(file.getOriginalFilename());
    if (acceptExtensions != null && !FilenameUtils.isExtension(fname, acceptExtensions)) {
        throw new ValidationException("file", "アップロードファイルには[{0}]を指定してください",
                new String[] { StringUtils.join(acceptExtensions) });
    }
    try {
        return new ReportFile(file.getOriginalFilename(), file.getBytes());
    } catch (IOException e) {
        throw new ValidationException("file", "アップロードファイルの解析に失敗しました");
    }
}
 
Example 10
Source File: FileUploadUtil.java    From springboot-learn with MIT License 5 votes vote down vote up
/**
 * 获取文件扩展名
 *
 * @param file 文件
 * @return
 */
public static String getFileExtention(MultipartFile file) {
    String extension = null;
    if (file != null && !file.isEmpty()) {
        String fileName = file.getOriginalFilename();
        extension = fileName.substring(fileName.lastIndexOf(".") + 1);
    }
    return extension;
}
 
Example 11
Source File: WebuiMailAttachmentsRepository.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
public LookupValue createAttachment(@NonNull final String emailId, @NonNull final MultipartFile file)
{
	//
	// Extract the original filename
	String originalFilename = file.getOriginalFilename();
	if (Check.isEmpty(originalFilename, true))
	{
		originalFilename = file.getName();
	}
	if (Check.isEmpty(originalFilename, true))
	{
		throw new AdempiereException("Filename not provided");
	}

	byte[] fileContent;
	try
	{
		fileContent = file.getBytes();
	}
	catch (IOException e)
	{
		throw new AdempiereException("Failed fetching attachment content")
				.setParameter("filename", originalFilename);
	}

	return createAttachment(emailId, originalFilename, fileContent);
}
 
Example 12
Source File: OssBootUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
     * 上传文件至阿里云 OSS
     * 文件上传成功,返回文件完整访问路径
     * 文件上传失败,返回 null
     *
     * @param file    待上传文件
     * @param fileDir 文件保存目录
     * @return oss 中的相对文件路径
     */
    public static String upload(MultipartFile file, String fileDir,String customBucket) {
        String FILE_URL = null;
        initOSS(endPoint, accessKeyId, accessKeySecret);
        StringBuilder fileUrl = new StringBuilder();
        String newBucket = bucketName;
        if(oConvertUtils.isNotEmpty(customBucket)){
            newBucket = customBucket;
        }
        try {
            //判断桶是否存在,不存在则创建桶
            if(!ossClient.doesBucketExist(newBucket)){
                ossClient.createBucket(newBucket);
            }
            // 获取文件名
            String orgName = file.getOriginalFilename();
            orgName = CommonUtils.getFileName(orgName);
            String fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            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://" + newBucket + "." + endPoint + "/" + fileUrl;
            }
            PutObjectResult result = ossClient.putObject(newBucket, fileUrl.toString(), file.getInputStream());
            // 设置权限(公开读)
//            ossClient.setBucketAcl(newBucket, CannedAccessControlList.PublicRead);
            if (result != null) {
                log.info("------OSS文件上传成功------" + fileUrl);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return FILE_URL;
    }
 
Example 13
Source File: BulkUploadService.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * convert multipart file to file
 *
 * @param multipartFile
 * @return File
 * @throws IOException
 */
private File convertToFile(MultipartFile multipartFile) throws IOException {
	File file = new File(multipartFile.getOriginalFilename());
	try (FileOutputStream fos = new FileOutputStream(file)) {
		fos.write(multipartFile.getBytes());
	}
	return file;
}
 
Example 14
Source File: StorageServiceImpl.java    From itweet-boot with Apache License 2.0 5 votes vote down vote up
@Override
public String store(MultipartFile file,String filePath,String columnd) throws SystemException {

    File f = new File(filePath);

    if (!f.exists()) {
        f.mkdirs();
    }

    String filename = file.getOriginalFilename();

    String suffix = filename.substring(filename.lastIndexOf(".")+1,filename.length());
    String ruleFilename = TimeMillisUtils.getTimeMillis()+"."+suffix;

    Path rootLocation = Paths.get(filePath);

    storeFile(file, filename, ruleFilename, rootLocation);

    Document document = new Document();
    document.setDate(new Date());
    document.setFilename(filename);
    document.setRuleFilename(ruleFilename);
    if ("".equals(columnd) || columnd == null) {
        document.setColumnd("article");
    } else {
        document.setColumnd(columnd);
    }
    document.setType(suffix);
    documentRepository.save(document);

    return ruleFilename;
}
 
Example 15
Source File: UploadUtil.java    From mumu with Apache License 2.0 5 votes vote down vote up
/**
    * 上传文件处理(支持批量)
    * @param request
    * @param pathDir 上传文件保存路径
    * @return
    * @throws IllegalStateException
    * @throws IOException
    */
public static List<String> uploadFile(HttpServletRequest request,String pathDir) throws IllegalStateException, IOException {
	CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
			request.getSession().getServletContext());
	List<String> fileNames = InstanceUtil.newArrayList();
	if (multipartResolver.isMultipart(request)) {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iterator = multiRequest.getFileNames();
		if(pathDir==null|| pathDir.equals("")){
			pathDir = request.getSession().getServletContext().getRealPath(uploadFileDir + DateUtils.currentTime());
		}
           File dirFile = new File(pathDir);
           if (!dirFile.isDirectory()) {
               dirFile.mkdirs();
           }
		while (iterator.hasNext()) {
			String key = iterator.next();
			MultipartFile multipartFile = multiRequest.getFile(key);
			if (multipartFile != null) {
				String uuid = UUID.randomUUID().toString().replace("-", "");
				String name = multipartFile.getOriginalFilename();
				int lastIndexOf = name.lastIndexOf(".");
				String postFix="";
				if(lastIndexOf!=-1){
					postFix = name.substring(lastIndexOf).toLowerCase();
				}
				String fileName = uuid + postFix;
				String filePath = pathDir + File.separator + fileName;
				File file = new File(filePath);
				file.setWritable(true, false);

				multipartFile.transferTo(file);
				fileNames.add(file.getAbsolutePath());
			}
		}
	}
	return fileNames;
}
 
Example 16
Source File: QiniuOssFileHandler.java    From halo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public UploadResult upload(MultipartFile file) {
    Assert.notNull(file, "Multipart file must not be null");

    Region region = optionService.getQiniuRegion();

    String accessKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_ACCESS_KEY).toString();
    String secretKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_SECRET_KEY).toString();
    String bucket = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_BUCKET).toString();
    String protocol = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_PROTOCOL).toString();
    String domain = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_DOMAIN).toString();
    String source = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_SOURCE, String.class, "");
    String styleRule = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_STYLE_RULE, String.class, "");
    String thumbnailStyleRule = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, "");

    // Create configuration
    Configuration configuration = new Configuration(region);

    // Create auth
    Auth auth = Auth.create(accessKey, secretKey);
    // Build put plicy
    StringMap putPolicy = new StringMap();
    putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"size\":$(fsize),\"width\":$(imageInfo.width),\"height\":$(imageInfo.height)}");
    // Get upload token
    String uploadToken = auth.uploadToken(bucket, null, 60 * 60, putPolicy);

    // Create temp path
    Path tmpPath = Paths.get(System.getProperty("java.io.tmpdir"), bucket);

    StringBuilder basePath = new StringBuilder(protocol)
        .append(domain)
        .append(URL_SEPARATOR);

    try {
        String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename()));
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String timestamp = String.valueOf(System.currentTimeMillis());
        StringBuilder upFilePath = new StringBuilder();
        if (StringUtils.isNotEmpty(source)) {
            upFilePath.append(source)
                .append(URL_SEPARATOR);
        }
        upFilePath.append(basename)
            .append("_")
            .append(timestamp)
            .append(".")
            .append(extension);

        // Get file recorder for temp directory
        FileRecorder fileRecorder = new FileRecorder(tmpPath.toFile());
        // Get upload manager
        UploadManager uploadManager = new UploadManager(configuration, fileRecorder);
        // Put the file
        Response response = uploadManager.put(file.getInputStream(), upFilePath.toString(), uploadToken, null, null);

        if (log.isDebugEnabled()) {
            log.debug("Qiniu oss response: [{}]", response.toString());
            log.debug("Qiniu oss response body: [{}]", response.bodyString());
        }

        // Convert response
        PutSet putSet = JsonUtils.jsonToObject(response.bodyString(), PutSet.class);

        // Get file full path
        String filePath = StringUtils.join(basePath.toString(), upFilePath.toString());

        // Build upload result
        UploadResult result = new UploadResult();
        result.setFilename(basename);
        result.setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule);
        result.setKey(upFilePath.toString());
        result.setSuffix(extension);
        result.setWidth(putSet.getWidth());
        result.setHeight(putSet.getHeight());
        result.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
        result.setSize(file.getSize());

        if (isImageType(result.getMediaType())) {
            if (ImageUtils.EXTENSION_ICO.equals(extension)) {
                result.setThumbPath(filePath);
            } else {
                result.setThumbPath(StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule);
            }
        }

        return result;
    } catch (IOException e) {
        if (e instanceof QiniuException) {
            log.error("Qiniu oss error response: [{}]", ((QiniuException) e).response);
        }

        throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到七牛云失败", e);
    }
}
 
Example 17
Source File: UploadFileService.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 4 votes vote down vote up
/**
 *  上传文件
 * @param f
 * @return
 */
@SneakyThrows
public UploadRecord upload(MultipartFile f) {
    String filename = f.getOriginalFilename();
    String name = filename.substring(0, filename.length() - 4);

    log.info("start upload..." + filename + "," + f.getSize());

    // 后缀校验
    check(filename.toLowerCase().endsWith(".log"), "unsupport.file.format");

    // 不能重名,防止重复提交
    check(uploadRecordDao.findByName(name) == null, "name.repeat");

    // 保存的目录
    String saveDir = ConfigUtil.get("PATH.LOGS");

    // 得到要保存的文件名
    String realName = generateFileName(saveDir, f);

    log.info("save to :" + saveDir + " , " + realName);

    // save file
    File newFile = new File(saveDir, realName);
    f.transferTo(newFile);

    // save record to db
    UploadRecord record = new UploadRecord();

    record.setName(name);
    record.setRealPath(realName);
    record.setSize(f.getSize());

    // 保存数据
    record = uploadRecordDao.save(record);

    // 分析文件
    int dataCount = parseLog(record.getId(), newFile);

    // 保存文件的记录数
    record.setDataCount(dataCount);
    record = uploadRecordDao.save(record);

    return record;
}
 
Example 18
Source File: ModelFileResource.java    From cubeai with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/modelfile/{taskUuid}", method = RequestMethod.POST, consumes = "multipart/form-data")
@Timed
public ResponseEntity<Void> uploadModelFile(MultipartHttpServletRequest request,
                                                       @PathVariable("taskUuid") String taskUuid) {
    log.debug("REST request to upload ucumos model file");

    String userLogin = JwtUtil.getUserLogin(request);

    MultipartFile multipartFile = request.getFile(userLogin);
    if (null == multipartFile) {
        return ResponseEntity.badRequest().headers(HeaderUtil.createAlert("No file provided", "file upload")).build();
    }

    String fileName = multipartFile.getOriginalFilename();
    long size = multipartFile.getSize();
    if (fileName == null || ("").equals(fileName) || size == 0) {
        return ResponseEntity.badRequest().headers(HeaderUtil.createAlert("No file content", "file upload")).build();
    }

    String userHome = System.getProperty("user.home");
    File file1 = new File(userHome + "/tempfile");
    if (!file1.exists()) {
        file1.mkdir();
    }

    File file2 = new File(userHome + "/tempfile/ucumosmodels");
    if (!file2.exists()) {
        file2.mkdir();
    }

    File file3 = new File(userHome + "/tempfile/ucumosmodels/" + userLogin);
    if (!file3.exists()) {
        file3.mkdir();
    }

    File file4 = new File(userHome + "/tempfile/ucumosmodels/" + userLogin + "/" + taskUuid);
    if (!file4.exists()) {
        file4.mkdir();
    }

    String[] tmpList = file4.list();

    for (String tmp : tmpList) {
        File tmpFile = new File(userHome + "/tempfile/ucumosmodels/" + userLogin + "/" + taskUuid + "/" + tmp);
        if (tmpFile.isFile()) {
            tmpFile.delete();
        }
    }

    File file5= new File(userHome + "/tempfile/ucumosmodels/" + userLogin + "/" + taskUuid + "/" + fileName);
    if (file5.exists()) {
        file5.delete();
    }
    try {
        multipartFile.transferTo(file5);
    } catch (IOException e) {
        e.printStackTrace();
        return ResponseEntity.badRequest().headers(HeaderUtil.createAlert("Save file failed", fileName)).build();
    }

    log.debug("Upload model file success: " + fileName + "," + size + "Bytes");
    request.getSession().setAttribute("msg", "Upload model file success");

    return ResponseEntity.ok().build();
}
 
Example 19
Source File: FileUtils.java    From paas with Apache License 2.0 4 votes vote down vote up
/**
 * 上传文件,如果是SpringBoot,配置如下:
 * # 上传单个文件最大允许
 * spring.servlet.multipart.max-file-size=10MB
 * # 每次请求最大允许
 * spring.servlet.multipart.max-request-size=100MB
 *
 * @return 自定义消息
 * @author jitwxs
 * @version 创建时间:2018年4月17日 下午4:05:26
 */
public static String upload(HttpServletRequest request) throws Exception {
    StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;

    // 遍历普通参数(即formData的fileName和fileSize)
    Enumeration<String> names = req.getParameterNames();
    while (names.hasMoreElements()) {
        String key = names.nextElement();
        String val = req.getParameter(key);
        System.out.println("FormField:k=" + key + "v=" + val);
    }

    // 遍历文件参数(即formData的file)
    Iterator<String> iterator = req.getFileNames();
    if (iterator == null){
        return "未选择文件";
    }
    String result = "";
    while (iterator.hasNext()) {
        MultipartFile file = req.getFile(iterator.next());
        String fileNames = file.getOriginalFilename();
        // 文件名
        fileNames = new String(fileNames.getBytes("UTF-8"));
        //int split = fileNames.lastIndexOf(".");
        // 文件前缀
        //String fileName = fileNames.substring(0, split);
        // 文件后缀
        //String fileType = fileNames.substring(split + 1, fileNames.length());
        // 文件大小
        //Long fileSize = file.getSize();
        // 文件内容
        byte[] content = file.getBytes();

        File file1 = new File("D:\\test\\"+fileNames);

        FileUtils.writeByteArrayToFile(file1, content);

        FileOutputStream fos = new FileOutputStream(file1);
        fos.write(content);
        fos.flush();
        result = "D:\\test\\"+fileNames;
        System.out.println("write success");
    }
    return result;
}
 
Example 20
Source File: FormDeploymentCollectionResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@ApiOperation(value = "Create a new form deployment", tags = {
        "Form Deployments" }, consumes = "multipart/form-data", produces = "application/json", notes = "The request body should contain data of type multipart/form-data. There should be exactly one file in the request, any additional files will be ignored. The deployment name is the name of the file-field passed in. Make sure the file-name ends with .form or .xml.")
@ApiResponses(value = {
        @ApiResponse(code = 201, message = "Indicates the form deployment was created."),
        @ApiResponse(code = 400, message = "Indicates there was no content present in the request body or the content mime-type is not supported for form deployment. The status-description contains additional information.")
})
@ApiImplicitParams({
    @ApiImplicitParam(name="file", paramType = "form", dataType = "java.io.File")
})
@PostMapping(value = "/form-repository/deployments", produces = "application/json", consumes = "multipart/form-data")
public FormDeploymentResponse uploadDeployment(@ApiParam(name = "tenantId") @RequestParam(value = "tenantId", required = false) String tenantId, HttpServletRequest request, HttpServletResponse response) {

    if (!(request instanceof MultipartHttpServletRequest)) {
        throw new FlowableIllegalArgumentException("Multipart request is required");
    }
    
    if (restApiInterceptor != null) {
        restApiInterceptor.executeNewDeploymentForTenantId(tenantId);
    }

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    if (multipartRequest.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("Multipart request with file content is required");
    }

    MultipartFile file = multipartRequest.getFileMap().values().iterator().next();

    try {
        FormDeploymentBuilder deploymentBuilder = formRepositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !fileName.endsWith(".form")) {
            fileName = file.getName();
        }

        if (fileName.endsWith(".form")) {
            deploymentBuilder.addInputStream(fileName, file.getInputStream());
        } else {
            throw new FlowableIllegalArgumentException("File must be of type .xml or .form");
        }
        deploymentBuilder.name(fileName);

        if (tenantId != null) {
            deploymentBuilder.tenantId(tenantId);
        }

        if (restApiInterceptor != null) {
            restApiInterceptor.enhanceDeployment(deploymentBuilder);
        }

        FormDeployment deployment = deploymentBuilder.deploy();
        response.setStatus(HttpStatus.CREATED.value());

        return formRestResponseFactory.createFormDeploymentResponse(deployment);

    } catch (Exception e) {
        if (e instanceof FlowableException) {
            throw (FlowableException) e;
        }
        throw new FlowableException(e.getMessage(), e);
    }
}