本文整理汇总了Java中org.springframework.web.multipart.MultipartHttpServletRequest.getFileNames方法的典型用法代码示例。如果您正苦于以下问题:Java MultipartHttpServletRequest.getFileNames方法的具体用法?Java MultipartHttpServletRequest.getFileNames怎么用?Java MultipartHttpServletRequest.getFileNames使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.springframework.web.multipart.MultipartHttpServletRequest
的用法示例。
在下文中一共展示了MultipartHttpServletRequest.getFileNames方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: upload
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
@RequestMapping(value = "/file/upload", method = RequestMethod.POST)
public Res upload(MultipartHttpServletRequest request) {
Res res = new Res();
try {
Iterator<String> it = request.getFileNames();
while (it.hasNext()) {
String uploadFile = it.next();
MultipartFile file = request.getFile(uploadFile);
FileUpload newFile = new FileUpload(file);
System.out.println("==============");
System.out.println(newFile);
fileService.uploadFile(file);
}
} catch (Exception e) {
res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
}
res.setStatus(HttpStatus.OK);
return res;
}
示例2: saveImage
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
public String saveImage(MultipartHttpServletRequest request) throws IOException {
UploadedFile ufile;
Iterator<String> itr = request.getFileNames();
MultipartFile mpf = request.getFile(itr.next());
String name = Calendar.getInstance().getTimeInMillis() + "";
String type = "jpg";
String originName = mpf.getOriginalFilename();
if (originName.contains(".")) {
String[] names = originName.split("\\.");
type = names[1];
}
ufile = new UploadedFile(mpf.getBytes(), name + "." + type, mpf.getContentType(),
mpf.getBytes().length);
String imagePath = "http://" + request.getServerName() + ":" + request.getServerPort() + "/user/image/" +
name + "/" + type;
return imagePath;
}
示例3: uploadFile
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
* 上传文件
* @param request
* @return
*/
public File uploadFile(HttpServletRequest request) {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
try {
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> iterator = multiRequest.getFileNames();
while (iterator.hasNext()) {
String key = iterator.next();
MultipartFile multipartFile = multiRequest.getFile(key);
if (multipartFile != null) {
String name = multipartFile.getOriginalFilename();
String pathDir = request.getSession().getServletContext().getRealPath("/upload/" + DateUtils.currentTime());
File dirFile = new File(pathDir);
if (!dirFile.isDirectory()) {
dirFile.mkdirs();
}
String filePath = pathDir+File.separator+name;
File file = new File(filePath);
file.setWritable(true, false);
multipartFile.transferTo(file);
return file;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例4: fileUpload
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
* 压测文件上传
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/fileUpload")
@ResponseBody
public ComponentResult<FileUploadBO> fileUpload(HttpServletRequest request,HttpServletResponse response) {
ComponentResult<FileUploadBO> componentResult = new ComponentResult<FileUploadBO>();
//1、获取上传参数
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> iterator = multiRequest.getFileNames();
while (iterator.hasNext()) {
MultipartFile file = multiRequest.getFile(iterator.next().toString());
if (null != file) {
//2、上传
String filename = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date()) + ".xls";
try {
File targetFile = new File(pressureDataFilepath + filename);
file.transferTo(targetFile);
//3、将本地文件上传到FTP
boolean uploadResult = ftpUtils.uploadFile(targetFile);
if(uploadResult){
componentResult.setData(new FileUploadBO(filename));
return ResultUtil.success(componentResult);
}else{
logger.error("文件上传FTP失败,filename:{}",filename);
return ResultUtil.fail(ErrorCode.FAIL,"文件上传FTP失败",componentResult);
}
} catch (IllegalStateException | IOException e) {
logger.error("上传文件异常,filename->" + filename,e);
}
}else{
logger.error("压测文件上传,file为NULL");
}
}
}else{
logger.error("压测文件上传,request校验失败");
}
//3、返回
return ResultUtil.fail(componentResult);
}
示例5: uploadFile
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
* 上传文件处理(支持批量)
* @param request
* @param pathDir 上传文件保存路径
* @return
* @throws IllegalStateException
* @throws IOException
*/
public static List<String> uploadFile(HttpServletRequest request,String pathDir) throws IllegalStateException, IOException {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
List<String> fileNames = new ArrayList<String>();
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> iterator = multiRequest.getFileNames();
if(pathDir==null|| pathDir.equals("")){
pathDir = request.getSession().getServletContext().getRealPath(uploadFileDir + DateUtils.currentTime());
}
File dirFile = new File(pathDir);
if (!dirFile.isDirectory()) {
dirFile.mkdirs();
}
while (iterator.hasNext()) {
String key = iterator.next();
MultipartFile multipartFile = multiRequest.getFile(key);
if (multipartFile != null) {
String uuid = UUID.randomUUID().toString().replace("-", "");
String name = multipartFile.getOriginalFilename();
int lastIndexOf = name.lastIndexOf(".");
String postFix="";
if(lastIndexOf!=-1){
postFix = name.substring(lastIndexOf).toLowerCase();
}
String fileName = uuid + postFix;
String filePath = pathDir + File.separator + fileName;
File file = new File(filePath);
file.setWritable(true, false);
multipartFile.transferTo(file);
fileNames.add(file.getAbsolutePath());
}
}
}
return fileNames;
}
示例6: uploadFile
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的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;
}
示例7: changePhoto
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
@RequestMapping(value="changePhoto.do", method={RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public ModelAndView changePhoto(HttpServletRequest request) throws IllegalStateException, IOException {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/MyHome/userCenter");
HttpSession s = request.getSession();
User user = (User) s.getAttribute("user");
// 得到文件
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);
try {
String filePath = path + "\\" + fileName;
System.err.println(filePath);
String name = new Date().toInstant().toString();
new Tool().upload(filePath, name);
user.setUserPhoto(String.valueOf("http://os8z6i0zb.bkt.clouddn.com/" + name));
userService.updateUser(user);
} catch (Exception e) {
modelAndView.addObject("infoMessage", "上传头像失败TAT");
return modelAndView;
}
modelAndView.addObject("infoMessage", "上传头像成功!");
return modelAndView;
}
示例8: adminAddAgent
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的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;
}
示例9: uploadFile
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
* 上传文件处理(支持批量)
* @param request
* @param pathDir 上传文件保存路径
* @return
* @throws IllegalStateException
* @throws IOException
*/
public static List<String> uploadFile(HttpServletRequest request,String pathDir) throws IllegalStateException, IOException {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
List<String> fileNames = InstanceUtil.newArrayList();
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> iterator = multiRequest.getFileNames();
if(pathDir==null|| pathDir.equals("")){
pathDir = request.getSession().getServletContext().getRealPath(uploadFileDir + DateUtils.currentTime());
}
File dirFile = new File(pathDir);
if (!dirFile.isDirectory()) {
dirFile.mkdirs();
}
while (iterator.hasNext()) {
String key = iterator.next();
MultipartFile multipartFile = multiRequest.getFile(key);
if (multipartFile != null) {
String uuid = UUID.randomUUID().toString().replace("-", "");
String name = multipartFile.getOriginalFilename();
int lastIndexOf = name.lastIndexOf(".");
String postFix="";
if(lastIndexOf!=-1){
postFix = name.substring(lastIndexOf).toLowerCase();
}
String fileName = uuid + postFix;
String filePath = pathDir + File.separator + fileName;
File file = new File(filePath);
file.setWritable(true, false);
multipartFile.transferTo(file);
fileNames.add(file.getAbsolutePath());
}
}
}
return fileNames;
}
示例10: doTestMultipartHttpServletRequest
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
private void doTestMultipartHttpServletRequest(MultipartHttpServletRequest request) throws IOException {
Set<String> fileNames = new HashSet<String>();
Iterator<String> fileIter = request.getFileNames();
while (fileIter.hasNext()) {
fileNames.add(fileIter.next());
}
assertEquals(2, fileNames.size());
assertTrue(fileNames.contains("file1"));
assertTrue(fileNames.contains("file2"));
MultipartFile file1 = request.getFile("file1");
MultipartFile file2 = request.getFile("file2");
Map<String, MultipartFile> fileMap = request.getFileMap();
List<String> fileMapKeys = new LinkedList<String>(fileMap.keySet());
assertEquals(2, fileMapKeys.size());
assertEquals(file1, fileMap.get("file1"));
assertEquals(file2, fileMap.get("file2"));
assertEquals("file1", file1.getName());
assertEquals("", file1.getOriginalFilename());
assertNull(file1.getContentType());
assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(), file1.getBytes()));
assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(),
FileCopyUtils.copyToByteArray(file1.getInputStream())));
assertEquals("file2", file2.getName());
assertEquals("myOrigFilename", file2.getOriginalFilename());
assertEquals("text/plain", file2.getContentType());
assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(), file2.getBytes()));
assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(),
FileCopyUtils.copyToByteArray(file2.getInputStream())));
}
示例11: upload
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
* 上传附件
* @param request
* @return
* @throws IllegalStateException
* @throws IOException
*/
public String upload(HttpServletRequest request) throws IllegalStateException, IOException {
ResourceBundle projectConfig = ResourceBundle.getBundle("config");
String filePath=projectConfig.getString("osframe.file.path");
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//记录上传过程起始时的时间,用来计算上传时间
int pre = (int) System.currentTimeMillis();
//取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if(file != null){
//取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
//如果名称不为“”,说明该文件存在,否则说明该文件不存在
if(myFileName.trim() !=""){
System.out.println(myFileName);
//重命名上传后的文件名
String fileName = "demoUpload\\" + file.getOriginalFilename();
//定义上传路径
String path = filePath+ fileName;//"E:\\upload\\"
File localFile = new File(path);
file.transferTo(localFile);
}
}
//记录上传该文件后的时间
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
}
}
return "/success";
}
示例12: parseInsertFileInfo
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
* 파일의 정보들을 재정의하여 저장
* @param map
* @param request
* @return
* @throws Exception
*/
public List<Map<String,Object>> parseInsertFileInfo(Map<String,Object> map, HttpServletRequest request) throws Exception{
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
Iterator<String> iterator = multipartHttpServletRequest.getFileNames();
MultipartFile multipartFile = null;
String originalFileName = null;
String originalFileExtension = null;
String storedFileName = null;
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); //다중파일 전송을 위한 리스트
Map<String, Object> listMap = null;
File file = new File(filePath);
if (file.exists() == false) {
file.mkdirs(); // 지정된위치에 폴더가 없으면 폴더생성
}
while(iterator.hasNext()){
multipartFile = multipartHttpServletRequest.getFile(iterator.next());
if(multipartFile.isEmpty() == false){
originalFileName = multipartFile.getOriginalFilename();
originalFileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
storedFileName = CommonUtils.getRandomString() + originalFileExtension; //랜덤파일이름+확장자 (서버에 저장될 이름)
file = new File(filePath + storedFileName);
multipartFile.transferTo(file); //파일저장
listMap = new HashMap<String,Object>();
listMap.put("BOARD_IDX", -1); //임시로 -1로 저장 -> 글 작성완료시 update
listMap.put("ORIGINAL_FILE_NAME", originalFileName);
listMap.put("STORED_FILE_NAME", storedFileName);
listMap.put("FILE_SIZE", multipartFile.getSize());
list.add(listMap);
}
}
return list;
}
示例13: upload
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
* 上传文件
* @param request
* @param dir
* @return
* @throws IllegalStateException
* @throws IOException
*/
public List<File> upload(File dir) throws IllegalStateException, IOException {
List<File> result = new ArrayList<File>();
HttpServletRequest request = getRequest();
// 创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 取得当前上传文件的文件名称
String fileName = file.getOriginalFilename();
// 如果名称不为"",说明该文件存在,否则说明该文件不存在
if (BasicUtil.isNotEmpty(fileName)) {
// 重命名上传后的文件名
String sufName = FileUtil.getSuffixFileName(fileName);
// 定义上传路径
File localFile = new File(dir,BasicUtil.getRandomLowerString(10)+"."+sufName);
file.transferTo(localFile);
result.add(localFile);
}
}
}
}
return result;
}
示例14: getMultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
* 从HttpServletRequest中获取MultipartFile
*/
private static MultipartFile getMultipartFile(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest =
(MultipartHttpServletRequest) request;
Iterator<String> fileNames = multipartRequest.getFileNames();
return multipartRequest.getFile(fileNames.next());
}
示例15: upload2
import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
* 向当前运行的war中上传文件
* @param upPath
* @param request
* @param response
* @return
* @throws IllegalStateException
* @throws IOException
*/
@RequestMapping("/upload")
public String upload2(HttpServletRequest request, HttpServletResponse response)
throws IllegalStateException, IOException {
// @RequestParam String upPath ,
log.info("upPath:[{}][{}]", request.getParameter("upPath"), request.getAttribute("upPath"));
String upPath = "/tpl/";
log.info("username[{}],upPath[{}]开始上传文件", SessionUtil.getUserInfo().getMember().getAccNo(), upPath);
String rootPath = request.getSession().getServletContext().getRealPath("/");
log.debug("获取到项目根路径为rootPath[{}]", rootPath);
ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());
Iterator<String> itr = multipartRequest.getFileNames();
MultipartFile file = null;
while (itr.hasNext()) {
file = multipartRequest.getFile(itr.next());
long pre = System.currentTimeMillis();
if (file != null) {
if (StringUtils.isNotBlank(file.getOriginalFilename())) {
String fileName = StringUtil.combinationString(upPath, "/", file.getOriginalFilename());
String path = rootPath + fileName;
File localFile = new File(path);
file.transferTo(localFile);
}
}
long finaltime = System.currentTimeMillis();
log.info("上传文件耗时:{}" , (finaltime - pre));
}
return "file/success";
}