org.springframework.web.multipart.MultipartFile类的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(11.0k)|赞(0)|评价(0)|浏览(640)

本文整理了Java中org.springframework.web.multipart.MultipartFile类的一些代码示例,展示了MultipartFile类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MultipartFile类的具体详情如下:
包路径:org.springframework.web.multipart.MultipartFile
类名称:MultipartFile

MultipartFile介绍

[英]A representation of an uploaded file received in a multipart request.

The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storage will be cleared at the end of request processing.
[中]在多部分请求中接收的上传文件的表示形式。
文件内容要么存储在内存中,要么临时存储在磁盘上。在这两种情况下,如果需要,用户负责将文件内容复制到会话级别或持久存储。临时存储将在请求处理结束时清除。

代码示例

代码示例来源:origin: stackoverflow.com

public File convert(MultipartFile file)
{    
  File convFile = new File(file.getOriginalFilename());
  convFile.createNewFile(); 
  FileOutputStream fos = new FileOutputStream(convFile); 
  fos.write(file.getBytes());
  fos.close(); 
  return convFile;
}

代码示例来源:origin: linlinjava/litemall

@PostMapping("/upload")
public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
  String originalFilename = file.getOriginalFilename();
  String url = storageService.store(file.getInputStream(), file.getSize(), file.getContentType(), originalFilename);
  Map<String, Object> data = new HashMap<>();
  data.put("url", url);
  return ResponseUtil.ok(data);
}

代码示例来源:origin: roncoo/spring-boot-demo

@RequestMapping(value = "upload")
@ResponseBody
public String upload(@RequestParam("roncooFile") MultipartFile file) {
  if (file.isEmpty()) {
    return "文件为空";
  String fileName = file.getOriginalFilename();
  logger.info("上传的文件名为:" + fileName);
    file.transferTo(dest);
    return "上传成功";
  } catch (IllegalStateException e) {

代码示例来源:origin: stackoverflow.com

public File multipartToFile(MultipartFile multipart) throws IllegalStateException, IOException 
{
    File convFile = new File( multipart.getOriginalFilename());
    multipart.transferTo(convFile);
    return convFile;
}

代码示例来源:origin: netgloo/spring-boot-samples

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
  @RequestParam("uploadfile") MultipartFile uploadfile) {
  String filename = uploadfile.getOriginalFilename();
  String directory = env.getProperty("netgloo.paths.uploadedFiles");
  String filepath = Paths.get(directory, filename).toString();
    new BufferedOutputStream(new FileOutputStream(new File(filepath)));
  stream.write(uploadfile.getBytes());
  stream.close();

代码示例来源:origin: ZHENFENG13/My-Blog

@ResponseBody
public RestResponseBo upload(HttpServletRequest request, @RequestParam("file") MultipartFile[] multipartFiles) throws IOException {
  UserVo users = this.user(request);
  Integer uid = users.getUid();
  try {
    for (MultipartFile multipartFile : multipartFiles) {
      String fname = multipartFile.getOriginalFilename();
      if (multipartFile.getSize() <= WebConst.MAX_FILE_SIZE) {
        String fkey = TaleUtils.getFileKey(fname);
        String ftype = TaleUtils.isImage(multipartFile.getInputStream()) ? Types.IMAGE.getType() : Types.FILE.getType();
        File file = new File(CLASSPATH + fkey);
        try {
          FileCopyUtils.copy(multipartFile.getInputStream(), new FileOutputStream(file));
        } catch (IOException e) {
          e.printStackTrace();

代码示例来源:origin: stackoverflow.com

MultipartFile file = model.getImageFile();
inputStream = file.getInputStream();
outputStream = new FileOutputStream(fullyFileName);

int readBytes = 0;
byte[] buffer = new byte[1024 * 50];
while ((readBytes = inputStream.read(buffer, 0, 1024 * 50)) != -1) {
  outputStream.write(buffer, 0, readBytes);
}

代码示例来源:origin: org.geowebcache/gwc-sqlite

private File handleFileUpload(MultipartFile uploadedFile, File workingDirectory)
    throws Exception {
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Handling file upload.");
  }
  // getting the uploaded file content
  File outputFile = new File(workingDirectory, UUID.randomUUID().toString());
  byte[] bytes = uploadedFile.getBytes();
  try (BufferedOutputStream stream =
      new BufferedOutputStream(new FileOutputStream(outputFile))) {
    stream.write(bytes);
  }
  return outputFile;
}

代码示例来源:origin: stackoverflow.com

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
MultipartFile multipartFile = multipartRequest.getFile("file");
byte[] content =multipartFile.getBytes();
File archivoParaGuardar= new File("/your_directory/"+multipartFile.getOriginalFilename());
try {
 baos.write(content);
 FileOutputStream fos = new FileOutputStream(archivoParaGuardar);
 baos.writeTo(fos);
 fos.close();
} catch (Exception e) {
 logger.error("Error saving file ", e);
}

代码示例来源:origin: pl.edu.icm.synat/synat-console-core

@RequestMapping(value = "/import/upload/local", method = RequestMethod.POST)
public String importClientPack(@RequestParam("file") MultipartFile file, Model model) {
  
  OutputStream outputStream = null;
  try {
    outputStream = new FileOutputStream(packRepoPath + file.getOriginalFilename());
    IOUtils.copy(file.getInputStream(), outputStream );
    outputStream.flush();
    notificationService.publishLocalizedNotification(NotificationLevel.INFO, "msg.import.file.upload.succesful");
  } catch (Exception e) {
    log.error(e.getMessage(), e);
    notificationService.publishLocalizedNotification(NotificationLevel.ERROR, "msg.import.file.upload.fail");
  } finally {
    IOUtils.closeQuietly(outputStream);
  }
  return REDIRECT_IMPORT_LIST;
}

代码示例来源:origin: bill1012/AdminEAP

@RequestMapping("/avatarUpload")
@ResponseBody
public AvatarResult avatarUpload(String userId, HttpServletRequest httpRequest, HttpSession session) throws Exception {
  Map<String, MultipartFile> fileMap = request.getFileMap();
  String contentType = request.getContentType();
  if (contentType.indexOf("multipart/form-data") >= 0) {
    AvatarResult result = new AvatarResult();
    String dirPath = request.getRealPath("/");
        inputStream = new BufferedInputStream(mFile.getInputStream());
        byte[] bytes = new byte[mFile.getInputStream().available()];
        inputStream.read(bytes);
        initParams = new String(bytes, "UTF-8");
        inputStream = new BufferedInputStream(mFile.getInputStream());
        outputStream = new BufferedOutputStream(new FileOutputStream(virtualPath.replace("/", "\\")));
        Streams.copy(inputStream, outputStream, true);
        inputStream.close();

代码示例来源:origin: bill1012/AdminEAP

public File createFile(MultipartFile file, String dirPath) {
  File dir = new File(dirPath);
  if (!dir.exists()) {
    dir.mkdir();
  }
  String filePath = dirPath + "/" + (new Date().getTime()) + "_" + file.getOriginalFilename();
  File newFile = new File(filePath);
  try {
    InputStream ins = file.getInputStream();
    OutputStream os = new FileOutputStream(newFile);
    int bytesRead = 0;
    byte[] buffer = new byte[1024];
    while ((bytesRead = ins.read(buffer, 0, 1024)) != -1) {
      os.write(buffer, 0, bytesRead);
    }
    os.close();
    ins.close();
  } catch (Exception e) {
    e.printStackTrace();
  }
  return newFile;
}

代码示例来源:origin: stackoverflow.com

@RequestMapping(value="/upload", method=RequestMethod.POST)
 public @ResponseBody String handleFileUpload( 
     @RequestParam("file") MultipartFile file){
     String name = "test11";
   if (!file.isEmpty()) {
     try {
       byte[] bytes = file.getBytes();
       BufferedOutputStream stream = 
           new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
       stream.write(bytes);
       stream.close();
       return "You successfully uploaded " + name + " into " + name + "-uploaded !";
     } catch (Exception e) {
       return "You failed to upload " + name + " => " + e.getMessage();
     }
   } else {
     return "You failed to upload " + name + " because the file was empty.";
   }
 }

代码示例来源:origin: tomoya92/pybbs

if (file == null || file.isEmpty()) return null;
String suffix = "." + file.getContentType().split("/")[1];
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(localPath)));
stream.write(file.getBytes());
stream.close();

代码示例来源:origin: joshlong/bootiful-banners

private File imageFileFrom(MultipartFile file) throws Exception {
    Assert.notNull(file);
    Assert.isTrue(Arrays.asList(MEDIA_TYPES).contains(file.getContentType().toLowerCase()));
    File tmp = File.createTempFile("banner-tmp-",
        "." + file.getContentType().split("/")[1]);
    try (InputStream i = new BufferedInputStream(file.getInputStream());
       OutputStream o = new BufferedOutputStream(new FileOutputStream(tmp))) {
      FileCopyUtils.copy(i, o);
      return tmp;
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

@RequestMapping(value = "/multipartfile", method = RequestMethod.POST)
public String processMultipartFile(@RequestParam(required = false) MultipartFile file,
    @RequestPart(required = false) Map<String, String> json, Model model) throws IOException {
  if (file != null) {
    model.addAttribute("fileContent", file.getBytes());
  }
  if (json != null) {
    model.addAttribute("jsonContent", json);
  }
  return "redirect:/index";
}

代码示例来源:origin: hs-web/hsweb-framework

/**
 * ueditor上传文件
 *
 * @return 上传结果
 * @throws IOException 文件上传错误
 */
@RequestMapping(method = RequestMethod.POST, consumes = "multipart/form-data")
@ApiOperation("上传文件")
public String upload(@RequestParam(value = "upfile", required = false) MultipartFile file) throws IOException {
  String fileName = file.getOriginalFilename();
  String suffix = FileType.getSuffixByFilename(fileName);
  String path = fileService.saveStaticFile(file.getInputStream(), System.currentTimeMillis() + suffix);
  State state = new BaseState(true);
  state.putInfo("size", file.getSize());
  state.putInfo("title",fileName);
  state.putInfo("url", path);
  state.putInfo("type", suffix);
  state.putInfo("original",fileName);
  return state.toJSONString();
}

代码示例来源:origin: stylefeng/Guns

/**
   * 上传图片
   *
   * @author fengshuonan
   * @Date 2018/12/24 22:44
   */
  @RequestMapping(method = RequestMethod.POST, path = "/upload")
  @ResponseBody
  public String upload(@RequestPart("file") MultipartFile picture) {

    String pictureName = UUID.randomUUID().toString() + "." + ToolUtil.getFileSuffix(picture.getOriginalFilename());
    try {
      String fileSavePath = gunsProperties.getFileUploadPath();
      picture.transferTo(new File(fileSavePath + pictureName));
    } catch (Exception e) {
      throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
    }
    return pictureName;
  }
}

代码示例来源:origin: sanluan/PublicCMS

@RequestMapping(params = "action=" + ACTION_UPLOAD)
public String upload(MultipartFile file, HttpServletRequest request, HttpSession session, ModelMap model) {
  SysSite site = getSite(request);
  if (null != file && !file.isEmpty()) {
    String originalName = file.getOriginalFilename();
    String suffix = fileComponent.getSuffix(originalName);
    String fileName = fileComponent.getUploadFileName(suffix);
      fileComponent.upload(file, siteComponent.getWebFilePath(site, fileName));
      logUploadService.save(new LogUpload(site.getId(), ControllerUtils.getAdminFromSession(session).getId(),
          LogLoginService.CHANNEL_WEB_MANAGER, originalName, LogUploadService.getFileType(suffix), file.getSize(),
          RequestUtils.getIpAddress(request), CommonUtils.getDate(), fileName));
      Map<String, Object> map = getResultMap(true);
      map.put("size", file.getSize());
      map.put("title", originalName);
      map.put("url", fileName);

代码示例来源:origin: spring-projects/spring-framework

@RequestMapping(value = "/spr13319", method = POST, consumes = "multipart/form-data")
  public ResponseEntity<Void> create(@RequestPart("file") MultipartFile multipartFile) {
    assertEquals("élève.txt", multipartFile.getOriginalFilename());
    return ResponseEntity.ok().build();
  }
}

相关文章