本文整理汇总了Java中org.springframework.web.multipart.MultipartFile.getOriginalFilename方法的典型用法代码示例。如果您正苦于以下问题:Java MultipartFile.getOriginalFilename方法的具体用法?Java MultipartFile.getOriginalFilename怎么用?Java MultipartFile.getOriginalFilename使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.springframework.web.multipart.MultipartFile
的用法示例。
在下文中一共展示了MultipartFile.getOriginalFilename方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: upload
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
@PostMapping
public @ResponseBody FileInfo upload(@RequestParam("myFile") MultipartFile file,
@RequestParam("message") String message) throws Exception {
String uuid = UUID.randomUUID().toString();
String filePath = FILES_BASE + uuid;
FileUtils.copyToFile(file.getInputStream(), new File(filePath));
String filename = file.getOriginalFilename();
String contentType = file.getContentType();
FileInfo fileInfo = new FileInfo(uuid, filename, message, contentType);
String json = mapper.writeValueAsString(fileInfo);
FileUtils.writeStringToFile(new File(filePath + "_meta.txt"), json, "utf-8");
return fileInfo;
}
示例2: upload
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
@PostMapping("/test/upload/handler")
public String upload(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
String destFile = new File(".").getCanonicalPath() + File.separator + file.getOriginalFilename();
InputStream in = file.getInputStream();
OutputStream out = new FileOutputStream(new File(destFile));
int read = 0;
byte[] bytes = new byte[1024];
while((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
return file.getOriginalFilename();
}
示例3: saveFile
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
/**
* 保存上传的文件
*
* @param file
* @return 文件下载的url
* @throws Exception
*/
public static String saveFile(MultipartFile file) throws Exception {
if (file == null || file.isEmpty())
return "";
File target = new File("file");
if (!target.isDirectory()) {
target.mkdirs();
}
String originalFilename = file.getOriginalFilename();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(file.getBytes());
String fileName = (Helper.bytesToHex(md.digest(),0,md.digest().length-1)) + "." + getPostfix(originalFilename);
File file1 = new File(target.getPath() + "/" + fileName);
Files.write(Paths.get(file1.toURI()), file.getBytes(), StandardOpenOption.CREATE_NEW);
return "/mall/admin/product/img/" + fileName;
}
示例4: 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";
}
示例5: Create
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
@PostMapping("/new")
public String Create(@ModelAttribute IncidentBean incident, @RequestParam("file") MultipartFile imageFile) {
LOG.info("creating incident");
IncidentBean result = incidentService.createIncident(incident);
String incidentID = result.getId();
if (imageFile != null) {
try {
String fileName = imageFile.getOriginalFilename();
if (fileName != null) {
//save the file
//now upload the file to blob storage
LOG.info("Uploading to blob");
String imageFileName = storageService.storeImage(incidentID, fileName, imageFile.getContentType(), imageFile.getBytes());
result.setImageUri(imageFileName);
incidentService.updateIncident( result);
}
} catch (Exception e) {
return "Incident/details";
}
return "redirect:/dashboard";
}
return "redirect:/dashboard";
}
示例6: addCrousCsvFile
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
/**
* Exemple :
* curl --form "[email protected]/tmp/le-csv.txt" http://localhost:8080/wsrest/nfc/addCrousCsvFile?authToken=123456
* @throws IOException
* @throws ParseException
*/
@RequestMapping(value = "/addCrousCsvFile", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<String> addCrousCsvFile(@RequestParam String authToken, @RequestParam MultipartFile file, @RequestParam String csn) throws IOException, ParseException {
HttpHeaders responseHeaders = new HttpHeaders();
String eppnInit = clientJWSController.getEppnInit(authToken);
if(eppnInit == null) {
log.info("Bad authotoken : " + authToken);
return new ResponseEntity<String>("bad authotoken", responseHeaders, HttpStatus.FORBIDDEN);
}
// sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
if(file != null) {
String filename = file.getOriginalFilename();
log.info("CrousSmartCardController retrieving file from rest call " + filename);
InputStream stream = new ByteArrayInputStream(file.getBytes());
Card card = Card.findCard(csn);
crousSmartCardService.consumeCsv(stream, false);
cardEtatService.setCardEtat(card, Etat.ENCODED, null, null, false, true);
if(appliConfigService.getEnableAuto()) {
cardEtatService.setCardEtatAsync(card.getId(), Etat.ENABLED, null, null, false, false);
}
return new ResponseEntity<String>("OK", responseHeaders, HttpStatus.OK);
}
return new ResponseEntity<String>("KO", responseHeaders, HttpStatus.BAD_REQUEST);
}
示例7: isValidImage
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
public static String isValidImage(HttpServletRequest request, MultipartFile file){
//最大文件大小
long maxSize = 5242880;
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
if(!ServletFileUpload.isMultipartContent(request)){
return "请选择文件";
}
if(file.getSize() > maxSize){
return "上传文件大小超过5MB限制";
}
//检查扩展名
String fileName=file.getOriginalFilename();
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
return "上传文件扩展名是不允许的扩展名\n只允许" + extMap.get("image") + "格式";
}
return "valid";
}
示例8: arrangement
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
@Transactional
@Override
public boolean arrangement(Homework homework, MultipartFile multipartFile) {
homework = homework.getInsWithGmt(homework);
homework.setPublishTime(new Date());
String fileName = multipartFile.getOriginalFilename();
homework.setFileName(fileName);
try {
homework.setUrl(PathUtils.saveFile(multipartFile.getInputStream(), fileName));
} catch (IOException e) {
e.printStackTrace();
return false;
}
return homeworkDao.insert(homework) > 0;
}
示例9: upload
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
/**
* Uploads a file.
*
* <p>
* File should be uploaded as multipart/form-data.
* </p>
* @param uploadFile Provided file with metadata
* @param index Should be the content of file indexed
* @return Reference to a stored file
*/
@ApiOperation(value = "Uploads a file and returns the reference to the stored file.",
notes = "File should be uploaded as multipart/form-data.",
response = FileRef.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful response", response = FileRef.class)})
@RequestMapping(value = "/", method = RequestMethod.POST)
public FileRef upload(@ApiParam(value = "Provided file with metadata", required = true)
@RequestParam("file") MultipartFile uploadFile,
@ApiParam(value = "Should be the content of file indexed")
@RequestParam(name = "index", defaultValue = "false") Boolean index) {
try (InputStream stream = uploadFile.getInputStream()) {
String filename = uploadFile.getOriginalFilename();
if (filename != null) {
filename = FilenameUtils.getName(filename);
}
String contentType = uploadFile.getContentType();
return repository.create(stream, filename, contentType, index);
} catch (IOException e) {
throw new BadArgument("file");
}
}
示例10: store
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
public UserFile store(User user, MultipartFile file) {
Path uploadFileRootPath = Paths.get(properties.getUploadFileRootPath());
String originalFilename = file.getOriginalFilename();
if (originalFilename == null) {
throw new StorageException("Name of the file should not be null");
}
String filename = StringUtils.cleanPath(originalFilename);
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + filename);
}
if (filename.contains("..")) { // This is a security check
throw new StorageException("Cannot store file with relative path outside current directory " + filename);
}
UserFile userFile = UserFile.of(file, user);
Path resolvedPath = uploadFileRootPath.resolve(userFile.getPath());
boolean mkdirs = resolvedPath.getParent().toFile().mkdirs();
if (!mkdirs) {
throw new StorageException("Failed to create directory for " + resolvedPath);
}
Files.copy(file.getInputStream(), resolvedPath, StandardCopyOption.REPLACE_EXISTING);
return userFileRepository.save(userFile);
}
catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
}
}
示例11: adminAddAgent
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
@RequestMapping(value="adminAddAgent.do", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView adminAddAgent(HttpServletRequest request, Agent agent) {
ModelAndView modelAndView = new ModelAndView();
HttpSession session = request.getSession();
agent.setPicUrl("http://os8z6i0zb.bkt.clouddn.com/defaultPhoto.png"); //设置默认头像
//插入用户上传的图片链接地址
try {
// 得到文件
String path = request.getSession().getServletContext().getRealPath("upload");
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator iter = multiRequest.getFileNames();
MultipartFile file = multiRequest.getFile(iter.next().toString());
String fileName = file.getOriginalFilename();
File dir = new File(path, fileName);
if (!dir.exists()) {
dir.mkdirs();
}
// MultipartFile自带的解析方法
file.transferTo(dir);
String filePath = path + "\\" + fileName;
System.err.println(filePath);
String name = new Date().toInstant().toString();
new Tool().upload(filePath, name);
agent.setPicUrl(String.valueOf("http://os8z6i0zb.bkt.clouddn.com/" + name));
} catch (Exception e) {
}
agentDao.insertAgent(agent); //插入数据
//更新显示层的经纪人列表
List<Agent> agentList = agentDao.selectAll();
session.setAttribute("agentList", agentList);
modelAndView.setViewName("SystemUser/managerAgent");
return modelAndView;
}
示例12: uploadFile
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
/** 上传文件处理(支持批量) */
public static List<String> uploadFile(HttpServletRequest request) {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
List<String> fileNames = InstanceUtil.newArrayList();
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
String pathDir = getUploadDir(request);
File dirFile = new File(pathDir);
if (!dirFile.isDirectory()) {
dirFile.mkdirs();
}
for (Iterator<String> iterator = multiRequest.getFileNames(); iterator.hasNext();) {
String key = iterator.next();
MultipartFile multipartFile = multiRequest.getFile(key);
if (multipartFile != null) {
String name = multipartFile.getOriginalFilename();
String uuid = UUID.randomUUID().toString();
String postFix = name.substring(name.lastIndexOf(".")).toLowerCase();
String fileName = uuid + postFix;
String filePath = pathDir + File.separator + fileName;
File file = new File(filePath);
file.setWritable(true, false);
try {
multipartFile.transferTo(file);
fileNames.add(fileName);
} catch (Exception e) {
logger.error(name + "保存失败", e);
}
}
}
}
return fileNames;
}
示例13: getPath
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
public static String getPath(MultipartFile multipartFile) {
String fileName = multipartFile.getOriginalFilename();
String format = DateFormatUtils.format(new Date(), "YYYY_MM_ddHHmmss");
String filePath = format + "_" + fileName;
LOGGER.info("fileName {} ",fileName);
uploadFilesUtil(filePath, multipartFile);
return getImagePath(filePath);
}
示例14: uploadImages
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
/**
* Upload an array of images to the server. Currently, the frontend can only handle an image at a time,
* but this method should only require a little modification if we wanted to make possible multiple uploads
* at the same time.
*
* @param files An array of files to upload.
* @return HTTP response of a body containing a JSON object with the generated path,
* using the appropriate status code.
*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<UploadImagesDTO> uploadImages(@RequestParam("files") MultipartFile[] files) {
String path;
UploadImagesDTO uploadFailed = new UploadImagesDTO("", false);
// Generate a random hex string that doesn't already exist
do {
path = getRandomHexString(16);
} while (dao.pathExists(path));
for (MultipartFile file : files) {
String name = file.getOriginalFilename();
try {
InputStream is = new BufferedInputStream(file.getInputStream());
String mimeType = URLConnection.guessContentTypeFromStream(is);
// Return if the image is not the right file type (or if it isn't even an image)
if (!ACCEPTED_FILE_TYPES.contains(mimeType)) {
dao.deleteAllImages(path);
return new ResponseEntity<>(uploadFailed, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
}
if (!dao.saveImage(name, file, path, mimeType)) {
// If saving an image fails for some reason, delete all previously uploaded images and
// return 500
dao.deleteAllImages(path);
return new ResponseEntity<>(uploadFailed, HttpStatus.INTERNAL_SERVER_ERROR);
}
} catch (IOException e) {
e.printStackTrace();
dao.deleteAllImages(path);
return new ResponseEntity<>(uploadFailed, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return new ResponseEntity<>(new UploadImagesDTO(path, true), HttpStatus.OK);
}
示例15: Attachment
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
public Attachment(MultipartFile file) throws IOException {
this.fileName = file.getOriginalFilename();
this.contentType = file.getContentType();
this.fileData = file.getBytes();
}