当前位置: 首页>>代码示例>>Java>>正文


Java MultipartFile类代码示例

本文整理汇总了Java中org.springframework.web.multipart.MultipartFile的典型用法代码示例。如果您正苦于以下问题:Java MultipartFile类的具体用法?Java MultipartFile怎么用?Java MultipartFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


MultipartFile类属于org.springframework.web.multipart包,在下文中一共展示了MultipartFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: upload

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
/**
 * 上传文件
 */
@RequestMapping("/upload")
@RequiresPermissions("sys:oss:all")
public R upload(@RequestParam("file") MultipartFile file) throws Exception {
	if (file.isEmpty()) {
		throw new RRException("上传文件不能为空");
	}

	//上传文件
	String url = OSSFactory.build().upload(file.getBytes());

	//保存文件信息
	SysOssEntity ossEntity = new SysOssEntity();
	ossEntity.setUrl(url);
	ossEntity.setCreateDate(new Date());
	sysOssService.save(ossEntity);

	return R.ok().put("url", url);
}
 
开发者ID:zhaoqicheng,项目名称:renren-fast,代码行数:22,代码来源:SysOssController.java

示例2: uploadAvatar

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
@RequestMapping(value = "/{id}/uploadAvatar", method = RequestMethod.POST)
@ApiOperation(value = "Add new upload Avatar")
public String uploadAvatar(@ApiParam(value = "user Id", required = true) @PathVariable("id") Integer id,
		@ApiParam(value = "Image File", required = true) @RequestPart("file") MultipartFile file) {

	String contentType = file.getContentType();
	if (!FileUploadUtil.isValidImageFile(contentType)) {
		return "Invalid image File! Content Type :-" + contentType;
	}
	File directory = new File(AVATAR_UPLOAD.getValue());
	if (!directory.exists()) {
		directory.mkdir();
	}
	File f = new File(userService.getAvatarUploadPath(id));
	try (FileOutputStream fos = new FileOutputStream(f)) {
		byte[] imageByte = file.getBytes();
		fos.write(imageByte);
		return "Success";
	} catch (Exception e) {
		return "Error saving avatar for User " + id + " : " + e;
	}
}
 
开发者ID:Code4SocialGood,项目名称:C4SG-Obsolete,代码行数:23,代码来源:UserController.java

示例3: player

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
public player(String playerId, String firstName, String lastName,
              String fullName, String alias, Date date, String email,
              String phoneNumber, String twitterHandle, String instagramHandle,
              String teamSelected, String teamCountry, String location, String reference,
              int playerGroup, String mailStatus, boolean fixtureGenerated, boolean inTables, MultipartFile image) {
    PlayerId = playerId;
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = fullName;
    this.alias = alias;
    this.date = date;
    this.email = email;
    this.phoneNumber = phoneNumber;
    this.twitterHandle = twitterHandle;
    this.instagramHandle = instagramHandle;
    this.teamSelected = teamSelected;
    this.teamCountry = teamCountry;
    this.location = location;
    this.reference = reference;
    this.playerGroup = playerGroup;
    this.mailStatus = mailStatus;
    this.fixtureGenerated = fixtureGenerated;
    this.inTables = inTables;
    this.image = image;
}
 
开发者ID:Recks11,项目名称:theLXGweb,代码行数:26,代码来源:player.java

示例4: generateFromHtml

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
@APIDeprecated(
    name = "/api/v1/pdf-generator/html",
    docLink = "https://github.com/hmcts/cmc-pdf-service#standard-api",
    expiryDate = "2018-02-08",
    note = "Please use `/pdfs` instead.")
@ApiOperation("Returns a PDF file generated from provided HTML/Twig template and placeholder values")
@PostMapping(
    value = "/html",
    consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
    produces = MediaType.APPLICATION_PDF_VALUE
)
public ResponseEntity<ByteArrayResource> generateFromHtml(
    @ApiParam("A HTML/Twig file. CSS should be embedded, images should be embedded using Data URI scheme")
    @RequestParam("template") MultipartFile template,
    @ApiParam("A JSON structure with values for placeholders used in template file")
    @RequestParam("placeholderValues") String placeholderValues
) {
    log.debug("Received a PDF generation request");
    byte[] pdfDocument = htmlToPdf.convert(asBytes(template), asMap(placeholderValues));
    log.debug("PDF generated");
    return ResponseEntity
        .ok()
        .contentLength(pdfDocument.length)
        .body(new ByteArrayResource(pdfDocument));
}
 
开发者ID:hmcts,项目名称:cmc-pdf-service,代码行数:26,代码来源:PDFGenerationEndpoint.java

示例5: uploadImHeadPortrait

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
/**
 * Im头像上传
 *
 * @param file
 * @return
 * @throws Exception
 */
@RequestMapping("uploadImHeadPortrait")
@ResponseBody
public PageData uploadImHeadPortrait(MultipartFile[] file) throws Exception {
    PageData pd = fileUpd(file);
    Object content = pd.get("content");
    PageData returnPd = new PageData();
    if (pd.getString("state").equals("200")) {
        String path = (String) ((HashMap) ((List) content).get(0)).get("path");
        String sltpath = (String) ((HashMap) ((List) content).get(0)).get("sltpath");
        PageData returnPd1 = new PageData();
        returnPd1.put("src", path);
        returnPd1.put("srcSlt", sltpath);
        returnPd.put("code", "0");
        returnPd.put("msg", "success");
        returnPd.put("data", returnPd1);
        return WebResult.requestSuccess(returnPd);
    } else {
        return WebResult.requestFailed(500, "服务器错误", pd.get("content"));
    }
}
 
开发者ID:noseparte,项目名称:Spring-Boot-Server,代码行数:28,代码来源:FilesUploadsRestful.java

示例6: update

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
/**
 * @api {patch} /credentials/:name Update
 * @apiParam {String} name Credential name to update
 *
 * @apiParamExample {multipart} RSA-Multipart-Body:
 *  the same as create
 *
 * @apiGroup Credenital
 */
@PatchMapping(path = "/{name}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@WebSecurity(action = Actions.ADMIN_UPDATE)
public Credential update(@PathVariable String name,
                         @RequestParam(name = "detail") String detailJson,
                         @RequestPart(name = "android-file", required = false) MultipartFile androidFile,
                         @RequestPart(name = "p12-files", required = false) MultipartFile[] p12Files,
                         @RequestPart(name = "pp-files", required = false) MultipartFile[] ppFiles) {

    // check name is existed
    if (!credentialService.existed(name)) {
        throw new IllegalParameterException("Credential name does not existed");
    }

    CredentialDetail detail = jsonConverter.getGsonForReader().fromJson(detailJson, CredentialDetail.class);
    return createOrUpdate(name, detail, androidFile, p12Files, ppFiles);
}
 
开发者ID:FlowCI,项目名称:flow-platform,代码行数:26,代码来源:CredentialController.java

示例7: upload

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
@ResponseBody
@RequestMapping(value = "upload.do",method = RequestMethod.POST)
public ServerResponse upload(HttpSession session,@RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request){
    // TODO: 2017/8/4 这个required = false是指upload_file不是必须加的吗?
    User user = (User) session.getAttribute(Const.CURRENT_USER);
    if (user == null){
        return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"请先登录");
    }
    //判断这个用户是不是管理员
    ServerResponse<String> checkRoleResult = iUserService.checkUserRole(user);
    if (checkRoleResult.isSuccess()){
        //tomcat发布以后,会在webapp下创建一个upload文件夹,与index.jsp和WEB-INF同级
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = iFileService.upload(file, path);
        String url = PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/")
                +fileName;
        Map map = Maps.newHashMap();
        map.put("uri",fileName);
        map.put("url",url);
        return ServerResponse.createBySuccess(map);
    } else {
        return ServerResponse.createByError("对不起,您没有管理员权限");
    }
}
 
开发者ID:wangshufu,项目名称:mmall,代码行数:25,代码来源:ProductManageController.java

示例8: testCreateFromDocuments

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
@Test
public void testCreateFromDocuments() throws Exception {
    List<MultipartFile> files = Stream.of(
        new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)),
        new MockMultipartFile("files", "filename.txt", "text/plain", "hello2".getBytes(StandardCharsets.UTF_8)))
        .collect(Collectors.toList());

    List<StoredDocument> storedDocuments = files.stream().map(f -> new StoredDocument()).collect(Collectors.toList());

    when(this.auditedStoredDocumentOperationsService.createStoredDocuments(files)).thenReturn(storedDocuments);

    restActions
        .withAuthorizedUser("userId")
        .withAuthorizedService("divorce")
        .postDocuments("/documents", files, Classifications.PUBLIC, null)
        .andExpect(status().isOk());

}
 
开发者ID:hmcts,项目名称:document-management-store-app,代码行数:19,代码来源:StoredDocumentControllerTests.java

示例9: saveUploadedFiles

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
private String saveUploadedFiles(List<MultipartFile> files) throws IOException {
    if (Files.notExists(Paths.get(UPLOADED_FOLDER))) {
        init();
    }

    String randomPath = "";

    for (MultipartFile file : files) {
        if (file.isEmpty()) {
            continue; //next pls
        }

        byte[] bytes = file.getBytes();

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

        randomPath +=  generateRandomPath() + "." + suffix;

        Path path = Paths.get(UPLOADED_FOLDER + randomPath);
        Files.write(path, bytes);
    }

    return randomPath;
}
 
开发者ID:ziwenxie,项目名称:leafer,代码行数:26,代码来源:FileUploadController.java

示例10: fileUpload

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
String fileUpload(MultipartFile file, ProjectFile pTarFile) {
    try {
        //decode
        pTarFile.setPFNotice(new String(pTarFile.getPFNotice().getBytes("iso-8859-1"), "UTF-8"));
        String realFileName = new String(file.getOriginalFilename().getBytes("iso-8859-1"), "UTF-8");
        String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1);
        String savaFileStr = DateTime.now().toString() + "." + suffix;
        String PFId = projectService.addFiletoUWid(savaFileStr, pTarFile, file);
        pTarFile.setPFId(PFId);
        //动态生成更新字段
        dynamicService.setProjectFileDynamic(pTarFile);
        return "ok";
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "error:您没有在该阶段上传的权限";
}
 
开发者ID:okingjerryo,项目名称:WeiMusicCommunity-server,代码行数:20,代码来源:WebController.java

示例11: upload

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
@RequestMapping("/upload.do")
public String upload(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException {
    for(MultipartFile file : myfiles){
        //此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了
        if(file.isEmpty()){
            System.out.println("文件未上传!");
        }
        else{
            //得到上传的文件名
            String fileName = file.getOriginalFilename();
            //得到服务器项目发布运行所在地址
            String path1 = request.getSession().getServletContext().getRealPath("file")+ File.separator;
            //  此处未使用UUID来生成唯一标识,用日期做为标识

             String path2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ fileName;
            request.getSession().setAttribute("document",path2);
             String path = path1+path2;
                    //查看文件上传路径,方便查找
            System.out.println(path);
            //把文件上传至path的路径
            File localFile = new File(path);
            file.transferTo(localFile);
        }
    }
    return "redirect:/student/uploadDocument";
}
 
开发者ID:junrui-zhao,项目名称:Educational-Management-System,代码行数:27,代码来源:GMStudentController.java

示例12: store

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
/**
 * The storing method should be able to adapt to all types of storing: requests, templates and responses from institutions
 *
 * @param files a list files that will be uploaded
 */
@Override
public boolean store(List<MultipartFile> files, Path path) {
    try {
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue; // give me another one
            }

            byte[] bytes = file.getBytes();

            Files.write(path, bytes);
        }
    } catch (IOException ioe) {
        logger.error(ioe.getStackTrace());

        return false;
    }

    return true;
}
 
开发者ID:CoruptiaUcide,项目名称:va-vedem-api,代码行数:26,代码来源:StorageServiceImpl.java

示例13: isPhoto

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
/**
 * 判断上传文件是否为图片
 * 
 * @param MultipartFile
 * @return NULL为TRUE
 */
public static boolean isPhoto(MultipartFile file) {
	if (file == null) {
		return false;
	}
	String originalFilename = file.getOriginalFilename();
	if (originalFilename == null || originalFilename.length() == 0) {
		return false;
	}
	// 获取文件后缀
	String fileSuffix = UploadUtil.getFileSuffix(originalFilename);
	if (fileSuffix == null || fileSuffix.length() == 0) {
		// 通过Mime类型获取文件类型
		fileSuffix = ContentTypeUtil.getFileTypeByMimeType(file.getContentType());
	}
	if(fileSuffix==null || fileSuffix.equals("")) {
		return false;
	}
	if(PhotoSuffix.indexOf(fileSuffix.toLowerCase()) != -1){
		return true;
	}
	return false;
}
 
开发者ID:ZiryLee,项目名称:FileUpload2Spring,代码行数:29,代码来源:UploadUtil.java

示例14: processUpload

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
/**
 * 上传发布流程定义.
 */
@RequestMapping("console-process-upload")
public String processUpload(@RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) throws Exception {
    String tenantId = tenantHolder.getTenantId();
    String fileName = file.getOriginalFilename();
    Deployment deployment = processEngine.getRepositoryService()
            .createDeployment()
            .addInputStream(fileName, file.getInputStream())
            .tenantId(tenantId).deploy();
    List<ProcessDefinition> processDefinitions = processEngine
            .getRepositoryService().createProcessDefinitionQuery()
            .deploymentId(deployment.getId()).list();

    for (ProcessDefinition processDefinition : processDefinitions) {
        processEngine.getManagementService().executeCommand(
                new SyncProcessCmd(processDefinition.getId()));
    }

    return "redirect:/bpm/console-listProcessDefinitions.do";
}
 
开发者ID:zhaojunfei,项目名称:lemon,代码行数:24,代码来源:ConsoleController.java

示例15: uploadFile

import org.springframework.web.multipart.MultipartFile; //导入依赖的package包/类
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public View uploadFile(@RequestParam("file") MultipartFile file) {
	try {
		InputStream input = file.getInputStream();
		this.messageManagementService.importFromExcel(input);
	} catch (Exception e) {
		LOG.error("error on uploading messages", e);
		return new RedirectView("../files.html?uploadSuccess=no&message=" + e.getMessage().toString());
	}
	return new RedirectView("../files.html?uploadSuccess=yes");
}
 
开发者ID:namics,项目名称:spring-i18n-support,代码行数:12,代码来源:FileController.java


注:本文中的org.springframework.web.multipart.MultipartFile类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。