Search in sources :

Example 91 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project gocd by gocd.

the class ArtifactsController method updateChecksumFile.

private boolean updateChecksumFile(MultipartHttpServletRequest request, JobIdentifier jobIdentifier, String filePath) throws IOException, IllegalArtifactLocationException {
    MultipartFile checksumMultipartFile = getChecksumFile(request);
    if (checksumMultipartFile != null) {
        String checksumFilePath = String.format("%s/%s/%s", artifactsService.findArtifactRoot(jobIdentifier), ArtifactLogUtil.CRUISE_OUTPUT_FOLDER, ArtifactLogUtil.MD5_CHECKSUM_FILENAME);
        File checksumFile = artifactsService.getArtifactLocation(checksumFilePath);
        synchronized (checksumFilePath.intern()) {
            return artifactsService.saveOrAppendFile(checksumFile, checksumMultipartFile.getInputStream());
        }
    } else {
        LOGGER.warn("[Artifacts Upload] Checksum file not uploaded for artifact at path '{}'", filePath);
    }
    return true;
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile)

Example 92 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project gocd by gocd.

the class FakeArtifactPublisherServlet method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    MultipartHttpServletRequest httpServletRequest = multipartResolver.resolveMultipart(request);
    Map<String, MultipartFile> map = httpServletRequest.getFileMap();
    MultipartFile multipartFile = map.values().iterator().next();
    receivedFiles.add(multipartFile.getOriginalFilename());
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) CommonsMultipartResolver(org.springframework.web.multipart.commons.CommonsMultipartResolver) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest)

Example 93 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project disconf by knightliao.

the class FileUploadValidator method validateFiles.

/**
 * 验证文件大小,文件名,文件后缀
 *
 * @param files
 * @param maxLength
 * @param allowExtName
 *
 * @return
 */
public List<MultipartFile> validateFiles(List<MultipartFile> files, long maxLength, String[] allowExtName) {
    List<MultipartFile> retFiles = new ArrayList<MultipartFile>();
    for (MultipartFile multipartFile : files) {
        try {
            this.validateFile(multipartFile, maxLength, allowExtName);
            retFiles.add(multipartFile);
        } catch (Exception e) {
            LOG.warn(e.toString());
        }
    }
    return retFiles;
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) ArrayList(java.util.ArrayList) FieldException(com.baidu.dsp.common.exception.FieldException)

Example 94 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project scoold by Erudika.

the class AdminController method restore.

@PostMapping("/import")
public String restore(@RequestParam("file") MultipartFile file, @RequestParam(required = false, defaultValue = "false") Boolean isso, HttpServletRequest req, HttpServletResponse res) {
    Profile authUser = utils.getAuthUser(req);
    if (!utils.isAdmin(authUser)) {
        res.setStatus(403);
        return null;
    }
    ObjectReader reader = ParaObjectUtils.getJsonMapper().readerFor(new TypeReference<List<Map<String, Object>>>() {
    });
    Map<String, String> comments2authors = new LinkedHashMap<>();
    int count = 0;
    int importBatchSize = Config.getConfigInt("import_batch_size", 100);
    String filename = file.getOriginalFilename();
    Sysprop s = new Sysprop();
    s.setType("scooldimport");
    try (InputStream inputStream = file.getInputStream()) {
        if (StringUtils.endsWithIgnoreCase(filename, ".zip")) {
            try (ZipInputStream zipIn = new ZipInputStream(inputStream)) {
                ZipEntry zipEntry;
                List<ParaObject> toCreate = new LinkedList<ParaObject>();
                while ((zipEntry = zipIn.getNextEntry()) != null) {
                    if (isso) {
                        count += importFromSOArchive(zipIn, zipEntry, reader, comments2authors).size();
                    } else if (zipEntry.getName().endsWith(".json")) {
                        List<Map<String, Object>> objects = reader.readValue(new FilterInputStream(zipIn) {

                            public void close() throws IOException {
                                zipIn.closeEntry();
                            }
                        });
                        objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
                        if (toCreate.size() >= importBatchSize) {
                            pc.createAll(toCreate);
                            toCreate.clear();
                        }
                        count += objects.size();
                    } else {
                        logger.error("Expected JSON but found unknown file type to import: {}", zipEntry.getName());
                    }
                }
                if (!toCreate.isEmpty()) {
                    pc.createAll(toCreate);
                }
                if (isso) {
                    updateSOCommentAuthors(comments2authors);
                }
            }
        } else if (StringUtils.endsWithIgnoreCase(filename, ".json")) {
            List<Map<String, Object>> objects = reader.readValue(inputStream);
            List<ParaObject> toCreate = new LinkedList<ParaObject>();
            objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
            count = objects.size();
            pc.createAll(toCreate);
        }
        s.setCreatorid(authUser.getCreatorid());
        s.setName(authUser.getName());
        s.addProperty("count", count);
        s.addProperty("file", filename);
        logger.info("Imported {} objects to {}. Executed by {}", count, Config.getConfigParam("access_key", "scoold"), authUser.getCreatorid() + " " + authUser.getName());
        if (count > 0) {
            pc.create(s);
        }
    } catch (Exception e) {
        logger.error("Failed to import " + filename, e);
        return "redirect:" + ADMINLINK + "?error=true&imported=" + count;
    }
    return "redirect:" + ADMINLINK + "?success=true&imported=" + count;
}
Also used : SIGNINLINK(com.erudika.scoold.ScooldServer.SIGNINLINK) Question(com.erudika.scoold.core.Question) RequestParam(org.springframework.web.bind.annotation.RequestParam) Arrays(java.util.Arrays) Webhook(com.erudika.para.core.Webhook) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) ParaClient(com.erudika.para.client.ParaClient) StringUtils(org.apache.commons.lang3.StringUtils) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) Model(org.springframework.ui.Model) Locale(java.util.Locale) Map(java.util.Map) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ParseException(java.text.ParseException) Config(com.erudika.para.core.utils.Config) ZipEntry(java.util.zip.ZipEntry) ScooldUtils(com.erudika.scoold.utils.ScooldUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) ParaObject(com.erudika.para.core.ParaObject) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ConfigValue(com.typesafe.config.ConfigValue) MediaType(org.springframework.http.MediaType) Set(java.util.Set) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) UUID(java.util.UUID) JsonMapper(com.fasterxml.jackson.databind.json.JsonMapper) SignedJWT(com.nimbusds.jwt.SignedJWT) Collectors(java.util.stream.Collectors) Comment(com.erudika.scoold.core.Comment) List(java.util.List) Tag(com.erudika.para.core.Tag) Optional(java.util.Optional) ADMINLINK(com.erudika.scoold.ScooldServer.ADMINLINK) App(com.erudika.para.core.App) Sysprop(com.erudika.para.core.Sysprop) ZipOutputStream(java.util.zip.ZipOutputStream) ParaObjectUtils(com.erudika.para.core.utils.ParaObjectUtils) ZipInputStream(java.util.zip.ZipInputStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) Pager(com.erudika.para.core.utils.Pager) Controller(org.springframework.stereotype.Controller) ArrayList(java.util.ArrayList) HOMEPAGE(com.erudika.scoold.ScooldServer.HOMEPAGE) Inject(javax.inject.Inject) LinkedHashMap(java.util.LinkedHashMap) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterInputStream(java.io.FilterInputStream) GetMapping(org.springframework.web.bind.annotation.GetMapping) LinkedList(java.util.LinkedList) Logger(org.slf4j.Logger) Post(com.erudika.scoold.core.Post) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) User(com.erudika.para.core.User) Utils(com.erudika.para.core.utils.Utils) DateUtils(org.apache.commons.lang3.time.DateUtils) TimeUnit(java.util.concurrent.TimeUnit) HttpStatus(org.springframework.http.HttpStatus) Reply(com.erudika.scoold.core.Reply) MultipartFile(org.springframework.web.multipart.MultipartFile) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) InputStream(java.io.InputStream) FilterInputStream(java.io.FilterInputStream) ZipInputStream(java.util.zip.ZipInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) Profile(com.erudika.scoold.core.Profile) LinkedList(java.util.LinkedList) ParseException(java.text.ParseException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) ZipInputStream(java.util.zip.ZipInputStream) ParaObject(com.erudika.para.core.ParaObject) Sysprop(com.erudika.para.core.Sysprop) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ParaObject(com.erudika.para.core.ParaObject) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 95 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project java-chassis by ServiceComb.

the class UploadSchema method fileUpload.

@PostMapping(path = "/fileUpload", produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String fileUpload(@RequestPart(name = "files") List<MultipartFile> files) {
    try {
        String fileName = UUID.randomUUID().toString();
        List<File> savedFiles = new ArrayList<>();
        int index = 0;
        for (MultipartFile file : files) {
            File tempFile = new File("random-server-" + fileName + index);
            savedFiles.add(tempFile);
            file.transferTo(tempFile);
            index++;
        }
        savedFiles.forEach(file -> file.delete());
        return "success";
    } catch (IOException e) {
        return "failed";
    }
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) ArrayList(java.util.ArrayList) IOException(java.io.IOException) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

MultipartFile (org.springframework.web.multipart.MultipartFile)272 File (java.io.File)151 IOException (java.io.IOException)71 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)71 MockMultipartFile (org.springframework.mock.web.MockMultipartFile)53 Test (org.junit.Test)41 FileInputStream (java.io.FileInputStream)37 ArrayList (java.util.ArrayList)30 JobConfig4DB (com.vip.saturn.job.console.mybatis.entity.JobConfig4DB)28 Test (org.junit.jupiter.api.Test)27 InputStream (java.io.InputStream)25 MultipartHttpServletRequest (org.springframework.web.multipart.MultipartHttpServletRequest)24 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)20 ByteArrayInputStream (java.io.ByteArrayInputStream)19 FileOutputStream (java.io.FileOutputStream)18 Date (java.util.Date)18 List (java.util.List)18 PostMapping (org.springframework.web.bind.annotation.PostMapping)17 MockMultipartFile (org.springframework.web.testfixture.servlet.MockMultipartFile)17 Path (java.nio.file.Path)15