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

The following examples show how to use org.springframework.web.multipart.MultipartFile#getInputStream() . 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: PDFUtil.java    From roncoo-education with MIT License 7 votes vote down vote up
/**
 * 水印
 */
public static void setWatermark(MultipartFile src, File dest, String waterMarkName, int permission) throws DocumentException, IOException {
	PdfReader reader = new PdfReader(src.getInputStream());
	PdfStamper stamper = new PdfStamper(reader, new BufferedOutputStream(new FileOutputStream(dest)));
	int total = reader.getNumberOfPages() + 1;
	PdfContentByte content;
	BaseFont base = BaseFont.createFont();
	for (int i = 1; i < total; i++) {
		content = stamper.getOverContent(i);// 在内容上方加水印
		content.beginText();
		content.setTextMatrix(70, 200);
		content.setFontAndSize(base, 30);
		content.setColorFill(BaseColor.GRAY);
		content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 400, 45);
		content.endText();
	}
	stamper.close();
}
 
Example 2
Source File: QiNiuCloudController.java    From SpringBoot-Home with Apache License 2.0 6 votes vote down vote up
/**
 * 获取图片宽高拼接字符串:?width=100&height=200
 * @return
 */
private String getWidthAndHeight(MultipartFile file){
    try {
        InputStream inputStream = file.getInputStream();
        BufferedImage image = ImageIO.read(inputStream);
        if (null == image){
            return "ERROR";
        }
        int width = image.getWidth();
        int height = image.getHeight();
        return "?width="+width+"&height="+height;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Source File: RequestPartServletServerHttpRequest.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream getBody() throws IOException {
	if (this.multipartRequest instanceof StandardMultipartHttpServletRequest) {
		try {
			return this.multipartRequest.getPart(this.partName).getInputStream();
		}
		catch (Exception ex) {
			throw new MultipartException("Could not parse multipart servlet request", ex);
		}
	}
	else {
		MultipartFile file = this.multipartRequest.getFile(this.partName);
		if (file != null) {
			return file.getInputStream();
		}
		else {
			String paramValue = this.multipartRequest.getParameter(this.partName);
			return new ByteArrayInputStream(paramValue.getBytes(determineEncoding()));
		}
	}
}
 
Example 4
Source File: PluginUploadFormToPluginUploadDtoConverter.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public PluginUploadDto convert(PluginUploadForm pluginUploadForm) {
	PluginUploadDto plugin = new PluginUploadDto();
	
	MultipartFile multipartFile = pluginUploadForm.getUploadPluginFile();
	
	try(InputStream is = multipartFile.getInputStream()) {
		File tmpFile = FileUtils.streamToTemporaryFile(is, multipartFile.getSize(), TMP_PLUGIN_FILE_PREFIX);
		plugin.setFile(tmpFile);
	} catch (IOException e) {
		logger.warn("Cannot create temporary file from uploaded plugin file");
		throw new RuntimeException("Cannot convert uploaded file", e);
	}
	
	return plugin;
}
 
Example 5
Source File: FileClient.java    From file-service with Apache License 2.0 6 votes vote down vote up
public String putObject(String bucketName, String originFileName, MultipartFile multipartFile) {
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    String fileName = FILE + "_" + uuid + "_" + originFileName;
    try {
        InputStream inputStream = multipartFile.getInputStream();
        if (isAwsS3) {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.addUserMetadata("Content-Type", "application/octet-stream");
            amazonS3.putObject(bucketName, fileName, inputStream, objectMetadata);
        } else {
            minioClient.putObject(bucketName, fileName, inputStream, "application/octet-stream");
        }
    } catch (Exception e) {
        throw new FileUploadException("error.file.upload", e);
    }
    return fileName;
}
 
Example 6
Source File: RequestPartServletServerHttpRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public InputStream getBody() throws IOException {
	if (this.multipartRequest instanceof StandardMultipartHttpServletRequest) {
		try {
			return this.multipartRequest.getPart(this.partName).getInputStream();
		}
		catch (Exception ex) {
			throw new MultipartException("Could not parse multipart servlet request", ex);
		}
	}
	else {
		MultipartFile file = this.multipartRequest.getFile(this.partName);
		if (file != null) {
			return file.getInputStream();
		}
		else {
			String paramValue = this.multipartRequest.getParameter(this.partName);
			return new ByteArrayInputStream(paramValue.getBytes(determineCharset()));
		}
	}
}
 
Example 7
Source File: ImportExcelUtil.java    From SpringBoot-Home with Apache License 2.0 6 votes vote down vote up
/**
 * 返回 ExcelReader
 *
 * @param excel         需要解析的 Excel 文件
 * @param excelListener new ExcelListener()
 */
private static ExcelReader getReader(MultipartFile excel, ExcelListener excelListener) {
    String filename = excel.getOriginalFilename();
    if (filename == null) {
        throw new ExcelException("文件格式错误!");
    }
    if (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx")) {
        throw new ExcelException("文件格式错误!");
    }
    InputStream inputStream;
    try {
        inputStream = new BufferedInputStream(excel.getInputStream());
        return new ExcelReader(inputStream, null, excelListener, false);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 8
Source File: ImageController.java    From paas with Apache License 2.0 5 votes vote down vote up
/**
 * 导入镜像【WebSocket】
 * @param file 镜像文件,只能为tar.gz文件
 * @param imageName 镜像名,不能包含大写字符
 * @param tag 镜像标签,默认为latest
 * @author jitwxs
 * @since 2018/7/25 13:41
 */
@PostMapping("/import")
@PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_SYSTEM')")
public ResultVO importImage(String imageName, @RequestParam(defaultValue = "latest") String tag, MultipartFile file,
                            @RequestAttribute String uid, HttpServletRequest request) {
    // 校验参数
    if(StringUtils.isBlank(imageName) || file == null) {
        return ResultVOUtils.error(ResultEnum.PARAM_ERROR);
    }
    // 判断镜像名是否有大写字符
    for(int i=0; i<imageName.length(); i++) {
        if(Character.isUpperCase(imageName.charAt(i))){
            return ResultVOUtils.error(ResultEnum.IMAGE_NAME_CONTAIN_UPPER);
        }
    }
    // 判断文件后缀
    if(!file.getOriginalFilename().endsWith(".tar.gz")) {
        return ResultVOUtils.error(ResultEnum.IMAGE_UPLOAD_ERROR_BY_SUFFIX);
    }

    // 拼接完整名:repo/userId/imageName:tag
    String fullName = "local/" + uid + "/" + imageName + ":" + tag;
    // 判断镜像是否存在
    if(imageService.getByFullName(fullName) != null) {
        return ResultVOUtils.error(ResultEnum.IMPORT_ERROR_BY_NAME);
    }

    try {
        InputStream stream = file.getInputStream();
        imageService.importImageTask(stream, fullName, uid, request);
        return ResultVOUtils.success("开始导入镜像");
    } catch (IOException e) {
        return ResultVOUtils.error(ResultEnum.IMPORT_ERROR_BY_NAME);
    }
}
 
Example 9
Source File: DamnYouServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
@Async
@Override
public void saveHistoryData(MultipartFile file) throws IOException {
    InputStream inputStream = file.getInputStream();
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    saveHistoryDataFromTxt(bufferedReader);
    bufferedReader.close();
}
 
Example 10
Source File: MinioController.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件到minio服务
 *
 * @param file
 * @return
 */
@PostMapping("upload")
public String upload(@RequestParam("file") MultipartFile file) {
    try {
        MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
        InputStream is = file.getInputStream(); //得到文件流
        String fileName = "/upload/img/" + file.getOriginalFilename(); //文件名
        String contentType = file.getContentType();  //类型
        minioClient.putObject(bucketName, fileName, is, contentType); //把文件放置Minio桶(文件夹)
        return "上传成功";
    } catch (Exception e) {
        return "上传失败";
    }
}
 
Example 11
Source File: DataPara.java    From Aooms with Apache License 2.0 5 votes vote down vote up
/**
 * 获取文件流
 * @return
 */
public InputStream getFileInputStream(String uploadName){
    try {
        MultipartFile file = getFile(uploadName);
        if(file == null){
            return null;
        }

        return file.getInputStream();
    } catch (IOException e) {
       throw new AoomsException("File InputStrem " + uploadName + " get error" , e);
    }
}
 
Example 12
Source File: ApiCommController.java    From easyweb with Apache License 2.0 5 votes vote down vote up
/**
     * 上传资料
     *
     * @return
     */
    @PostMapping("/upload")
    public BaseResult upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        _log.debug("进入文件上传控制器");
        BaseResult result = new BaseResult(BaseResultCode.EXCEPTION, "上传失败!");
        if (!file.isEmpty()) {
            String fileOldName = file.getOriginalFilename();
            //获取文件后缀名
            String prefix = fileOldName.substring(fileOldName.lastIndexOf(".") + 1);
            String fileName = IdGen.uuid() + "." + prefix;
            _log.debug("文件名:"+fileName);
            try {
                _log.debug("开始上传文件");
                InputStream inputStream = file.getInputStream();
                boolean isOk = FtpUtil.uploadFile(ftpConfig.getHost(), ftpConfig.getUser(), ftpConfig.getPwd(), "upload", "/files", fileName, inputStream);
                if (isOk) {
                    result = new BaseResult(BaseResultCode.SUCCESS, "upload/files/" + fileName);
                }
//                FileUtil.uploadFile(file.getBytes(), filePath, fileName);
            } catch (Exception e) {
                // TODO: handle exception
                _log.error("文件上传失败!"+e.getMessage());
                result = new BaseResult(BaseResultCode.EXCEPTION, "上传失败");
            }
        } else {
            _log.error("不允许上传空文件");
            result = new BaseResult(BaseResultCode.EXCEPTION, "上传失败,因为文件是空的");
        }
        return result;
    }
 
Example 13
Source File: UploadUtil.java    From spring-boot-plus with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件
 *
 * @param uploadPath           上传目录
 * @param multipartFile        上传文件
 * @param uploadFileNameHandle 回调
 * @return
 * @throws Exception
 */
public static String upload(String uploadPath, MultipartFile multipartFile, UploadFileNameHandle uploadFileNameHandle) throws Exception {
    // 获取输入流
    InputStream inputStream = multipartFile.getInputStream();
    // 文件保存目录
    File saveDir = new File(uploadPath);
    // 判断目录是否存在,不存在,则创建,如创建失败,则抛出异常
    if (!saveDir.exists()) {
        boolean flag = saveDir.mkdirs();
        if (!flag) {
            throw new RuntimeException("创建" + saveDir + "目录失败!");
        }
    }

    String originalFilename = multipartFile.getOriginalFilename();
    String saveFileName;
    if (uploadFileNameHandle == null) {
        saveFileName = new DefaultUploadFileNameHandleImpl().handle(originalFilename);
    } else {
        saveFileName = uploadFileNameHandle.handle(originalFilename);
    }
    log.info("saveFileName = " + saveFileName);

    File saveFile = new File(saveDir, saveFileName);
    // 保存文件到服务器指定路径
    FileUtils.copyToFile(inputStream, saveFile);
    return saveFileName;
}
 
Example 14
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 15
Source File: QETag.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
public String calcETag(MultipartFile file) throws IOException,
        NoSuchAlgorithmException {
    String etag = "";
    long fileLength = file.getSize();
    InputStream inputStream = file.getInputStream();
    etag = calcETag(inputStream,fileLength);
    return etag;
}
 
Example 16
Source File: HeritFileUploadUtil.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
     * 파일을 Upload 처리한다.
     *
     * @param request
     * @param where
     * @param maxFileSize
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List<HeritFormBasedFileVO> uploadFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception {
    	List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

		MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
		Iterator fileIter = mptRequest.getFileNames();

		while (fileIter.hasNext()) {
		    MultipartFile mFile = mptRequest.getFile((String)fileIter.next());
		    HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

		    String tmp = mFile.getOriginalFilename();

	            if (tmp.lastIndexOf("\\") >= 0) {
	        	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
	            }

	            vo.setFieldName(mFile.getName());
	            vo.setFileName(tmp);
	            vo.setContentType(mFile.getContentType());
	            //서브디렉토리 주석처리
//	            vo.setServerSubPath(getTodayString());
	            vo.setPhysicalName(getPhysicalFileName());
	            vo.setSize(mFile.getSize());
	            //System.out.println("size : " + mFile.getSize());

	            if (tmp.lastIndexOf(".") >= 0) {
	       	 		vo.setPhysicalName(vo.getPhysicalName());	// 2012.11 KISA 보안조치
	            }

	            if (mFile.getSize() >= 0) {
	            	InputStream is = null;
	            	//System.out.println("size : " + mFile.getSize());
	            	try {
	            		is = mFile.getInputStream();
//	            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getServerSubPath()+SEPERATOR+vo.getPhysicalName())));
	            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getPhysicalName())));
	            		//System.out.println("saveFile Name : "+vo.getPhysicalName());
	            	} finally {
	            		if (is != null) {
	            			is.close();
	            		}
	            	}
	            	list.add(vo);
	            }
		}

		return list;
    }
 
Example 17
Source File: CodeFirstSpringmvc.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@PostMapping(path = "/upload1", produces = MediaType.TEXT_PLAIN_VALUE)
public String fileUpload1(@RequestPart(name = "file1") MultipartFile file1) throws IOException {
  try (InputStream is = file1.getInputStream()) {
    return IOUtils.toString(is, StandardCharsets.UTF_8);
  }
}
 
Example 18
Source File: PortraitSaveController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
    * Upload portrait image.
    */
   @RequestMapping(path = "", method = RequestMethod.POST)
   public String unspecified(@ModelAttribute("PortraitActionForm") PortraitActionForm portraitForm,
    HttpServletRequest request, HttpServletResponse response)
    throws IOException, InvalidParameterException, RepositoryCheckedException {
MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();

MultipartFile file = portraitForm.getFile();
String fileName = file.getOriginalFilename();
log.debug("got file: " + fileName + " of type: " + file.getContentType() + " with size: " + file.getSize());

User user = userManagementService.getUserByLogin(request.getRemoteUser());

// check if file is an image using the MIME content type
String mediaType = file.getContentType().split("/", 2)[0];
if (!mediaType.equals("image")) {
    errorMap.add("file", messageService.getMessage("error.portrait.not.image"));
    request.setAttribute("errorMap", errorMap);
    return "forward:/index.do?redirect=portrait";
}

// check file exists
InputStream is = file.getInputStream();
if (is == null) {
    errorMap.add("file", messageService.getMessage("error.general.1"));
    request.setAttribute("errorMap", errorMap);
    return "forward:/index.do?redirect=portrait";
}

// write to content repository
NodeKey originalFileNode = null;
if ((file != null) && !StringUtils.isEmpty(fileName)) {

    //Create nice file name. If file name equals to "blob" - it means it was uploaded using webcam
    String fileNameWithoutExt;
    if (fileName.equals("blob")) {
	HttpSession ss = SessionManager.getSession();
	UserDTO userDTO = (UserDTO) ss.getAttribute(AttributeNames.USER);
	fileNameWithoutExt = userDTO.getLogin() + "_portrait";

    } else {
	fileNameWithoutExt = fileName.substring(0, fileName.indexOf('.'));
    }

    // upload to the content repository
    originalFileNode = centralToolContentHandler.uploadFile(is, fileNameWithoutExt + "_original.jpg",
	    "image/jpeg");
    is.close();
    log.debug("saved file with uuid: " + originalFileNode.getUuid() + " and version: "
	    + originalFileNode.getVersion());

    //resize to the large size
    is = ResizePictureUtil.resize(file.getInputStream(), CommonConstants.PORTRAIT_LARGEST_DIMENSION_LARGE);
    NodeKey node = centralToolContentHandler.updateFile(originalFileNode.getUuid(), is,
	    fileNameWithoutExt + "_large.jpg", "image/jpeg");
    is.close();
    log.debug("saved file with uuid: " + node.getUuid() + " and version: " + node.getVersion());

    //resize to the medium size
    is = ResizePictureUtil.resize(file.getInputStream(), CommonConstants.PORTRAIT_LARGEST_DIMENSION_MEDIUM);
    node = centralToolContentHandler.updateFile(node.getUuid(), is, fileNameWithoutExt + "_medium.jpg",
	    "image/jpeg");
    is.close();
    log.debug("saved file with uuid: " + node.getUuid() + " and version: " + node.getVersion());

    //resize to the small size
    is = ResizePictureUtil.resize(file.getInputStream(), CommonConstants.PORTRAIT_LARGEST_DIMENSION_SMALL);
    node = centralToolContentHandler.updateFile(node.getUuid(), is, fileNameWithoutExt + "_small.jpg",
	    "image/jpeg");
    is.close();
    log.debug("saved file with uuid: " + node.getUuid() + " and version: " + node.getVersion());

}

// delete old portrait file (we only want to keep the user's current portrait)
if (user.getPortraitUuid() != null) {
    centralToolContentHandler.deleteFile(user.getPortraitUuid());
}
user.setPortraitUuid(originalFileNode.getUuid());
userManagementService.saveUser(user);

return "forward:/index.do?redirect=portrait";
   }
 
Example 19
Source File: OutcomeService.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
   @SuppressWarnings("unchecked")
   public int importOutcomes(MultipartFile fileItem) throws IOException {
int counter = 0;
POIFSFileSystem fs = new POIFSFileSystem(fileItem.getInputStream());
try (HSSFWorkbook wb = new HSSFWorkbook(fs)) {
    HSSFSheet sheet = wb.getSheetAt(0);
    int startRow = sheet.getFirstRowNum();
    int endRow = sheet.getLastRowNum();
    User user = null;

    // make import work with files with header ("exported on") or without (pure data)
    HSSFRow row = sheet.getRow(startRow);
    HSSFCell cell = row.getCell(0);
    String header = cell.getStringCellValue();
    startRow += "name".equalsIgnoreCase(header) ? 1 : 5;

    for (int i = startRow; i < (endRow + 1); i++) {
	row = sheet.getRow(i);
	cell = row.getCell(1);
	String code = cell.getStringCellValue();
	List<Outcome> foundOutcomes = outcomeDAO.findByProperty(Outcome.class, "code", code);
	if (!foundOutcomes.isEmpty()) {
	    if (log.isDebugEnabled()) {
		log.debug("Skipping an outcome with existing code: " + code);
	    }
	    continue;
	}
	cell = row.getCell(3);
	String scaleCode = cell.getStringCellValue();
	List<OutcomeScale> foundScales = outcomeDAO.findByProperty(OutcomeScale.class, "code", scaleCode);
	OutcomeScale scale = foundScales.isEmpty() ? null : foundScales.get(0);
	if (scale == null) {
	    if (log.isDebugEnabled()) {
		log.debug("Skipping an outcome with missing scale with code: " + scaleCode);
	    }
	    continue;
	}
	cell = row.getCell(0);
	String name = cell.getStringCellValue();
	cell = row.getCell(2);
	String description = cell == null ? null : cell.getStringCellValue();

	Outcome outcome = new Outcome();
	outcome.setName(name);
	outcome.setCode(code);
	outcome.setDescription(description);
	outcome.setScale(scale);
	if (user == null) {
	    UserDTO userDTO = OutcomeService.getUserDTO();
	    user = (User) outcomeDAO.find(User.class, userDTO.getUserID());
	}
	outcome.setCreateBy(user);
	outcome.setCreateDateTime(new Date());
	outcomeDAO.insert(outcome);

	counter++;
    }
}
return counter;
   }
 
Example 20
Source File: ImportExcelUtils.java    From MicroCommunity with Apache License 2.0 2 votes vote down vote up
/**
 * 创建WorkBook对象
 *
 * @param uploadFile
 * @return
 * @throws IOException
 */
public static final Workbook createWorkbook(MultipartFile uploadFile) throws IOException {
    return new XSSFWorkbook(uploadFile.getInputStream());
}