本文整理汇总了Java中org.springframework.web.multipart.MultipartFile.transferTo方法的典型用法代码示例。如果您正苦于以下问题:Java MultipartFile.transferTo方法的具体用法?Java MultipartFile.transferTo怎么用?Java MultipartFile.transferTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.springframework.web.multipart.MultipartFile
的用法示例。
在下文中一共展示了MultipartFile.transferTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: copyMultipartFileToFile
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
public static String copyMultipartFileToFile(String baseDir,
MultipartFile multipartFile, String spaceName, String targetFileName)
throws Exception {
if (targetFileName == null) {
return copyMultipartFileToFile(baseDir, multipartFile, spaceName);
}
if (targetFileName.indexOf("../") != -1) {
logger.info("invalid : {}", targetFileName);
throw new IllegalStateException("invalid : " + targetFileName);
}
File file = findTargetFile(baseDir, spaceName, targetFileName);
multipartFile.transferTo(file);
return targetFileName;
}
示例2: doPost
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
public static String doPost(String id, MultipartFile multipartFile) throws IOException{
OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
long currentTime = System.currentTimeMillis();
String filename = id + String.valueOf(currentTime)+".png";
//创建缓存文件
File f = null;
f = File.createTempFile("tmp", null);
multipartFile.transferTo(f);
//缓存文件上传至OSS
InputStream inputStream = new FileInputStream(f);
ossClient.putObject("zxbangban", filename, inputStream);
//关闭OSS实例,删除临时文件
ossClient.shutdown();
f.deleteOnExit();
return filename;
}
示例3: uploadFile
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的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: uploadFile
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
public static Boolean uploadFile(HttpServletRequest request, MultipartFile file,String format) {
System.out.println("开始");
String path =request.getSession().getServletContext().getRealPath("/")+Constant.ZIP_FILE_FOLDER + File.separator;
String fileName = file.getOriginalFilename();
System.out.println(path);
if (format.equals(Constant.FILE_FORMATE_ZIP)) {
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}else {
return false;
}
}
示例5: 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";
}
示例6: multipartFileToTempFile
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
public static boolean multipartFileToTempFile(String fileName,MultipartFile multipartFile){
String destination = fileName;
File file = new File(destination);
try{
multipartFile.transferTo(file);
}catch(Exception e){
return false;
}
return true;
}
示例7: convertIfcToGlb
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
@RequestMapping(value = "convertIfcToGlb", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> convertIfcToGlb(@RequestParam(value = "file", required = true) MultipartFile file,
HttpServletRequest request, HttpServletResponse response) throws IOException {//不存档
ResultUtil result = new ResultUtil();
String path = request.getSession().getServletContext().getRealPath("upload/ifc/");
String fileName = file.getOriginalFilename();
String[] split = fileName.split("\\.");
String suffix = null;
if (split.length >= 2) {
suffix = split[split.length - 1];
}
if (suffix == null || !suffix.equals("ifc")) {
result.setSuccess(false);
result.setMsg("suffix : " + suffix + " is not be supported");
return result.getResult();
}
String newFileName = fileName.substring(0, fileName.lastIndexOf("."));
newFileName += "-" + System.currentTimeMillis();
newFileName += "." + suffix;
File targetFile = new File(path, newFileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
Long glbId = bimService.convertIfcToGlbOffline(targetFile);
result.setSuccess(true);
result.setKeyValue("glbId", glbId);;
return result.getResult();
}
示例8: upload
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
public String upload(MultipartFile file,String path){
//获取用户上传图片的原始文件名
String originalFilename = file.getOriginalFilename();
//原图片名为abc.fff.jpg,originalFilename.substring(originalFilename.lastIndexOf("."))--->.jpg;所以得+1才能得到jpg
//图片后缀/格式-->jpg
String extensionFile = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
//因为不同的用户有可能上传的图片名一样,所以我们的图片名得改成唯一的
String fileName = UUID.randomUUID()+"."+extensionFile;
logger.info("开始上传文件,上传文件的文件名为{},上传的路径为{},新的文件名为{}",originalFilename,path,fileName);
File fileDir = new File(path);
if (!fileDir.exists()){
//设置文件可写权限
fileDir.setWritable(true);
//多个级别的文件夹
fileDir.mkdirs();
}
//目标文件
File targetFile = new File(path,fileName);
try {
//将文件上传到tomcat的upload文件夹下
file.transferTo(targetFile);
//将tomcat上的文件上传到FTP文件服务器上
FTPUtil.uploadFiles(Lists.newArrayList(targetFile));
//删除tomcat下的文件,防止tomcat负载过大
targetFile.delete();
} catch (IOException e) {
logger.error("上传文件失败",e);
return null;
}
return targetFile.getName();
}
示例9: upload
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
@Override
public String upload(final MultipartFile uploadedFile) {
if (uploadedFile.isEmpty()) {
throw new FileUploadException("Error during upload image. Uploading file is empty!");
}
final File file = new File(root + "/" + UUID.randomUUID().toString());
try {
uploadedFile.transferTo(file);
return file.getName();
} catch (IOException e) {
throw new FileUploadException(e.getLocalizedMessage());
}
}
示例10: saveFile
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
private void saveFile(MultipartFile picFile, String filePath) throws IOException {
String originalName = picFile.getOriginalFilename();
System.out.print(originalName);
String newFileName = UUID.randomUUID()+originalName.substring(originalName.lastIndexOf("."));
File file = new File(filePath,newFileName);
System.out.print(file.getAbsolutePath());
file.createNewFile();
picFile.transferTo(file);
}
示例11: userRegist
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
@RequestMapping(method=RequestMethod.POST)
public ModelAndView userRegist(@Valid User reguser, BindingResult result,
MultipartFile idPicPath,
HttpServletRequest request) throws Exception{
ModelAndView mv = new ModelAndView();
//if(result.hasErrors()){
// mv.setViewName("useradd");
//}else{
// ��ȡWebContent����Ŀ¼���·��
String path = request.getServletContext().getRealPath("/upload");
// �����ϴ���ͼƬ�ļ�
String fileName = idPicPath.getOriginalFilename(); // ԭʼ�ļ���
// �ļ��� = "����ַ������" + ".����"
String ext = FilenameUtils.getExtension(fileName);
fileName = UUID.randomUUID().toString() + "." + ext;
//System.currentTimeMillis()
//Math.random() * 100000
File file =
new File(path + "/" + fileName);
idPicPath.transferTo(file); // "���Ϊ"ָ��Ŀ���ļ�
reguser.setIdpicpath("upload/" + fileName); // �ļ����·��(д����ݿ�)
int count = userService.insertUser(reguser);
if(count > 0) {
// ע��ɹ�����ת���û��б�ҳ��
// �ض��� response.sendRedirect("/user");
mv.setViewName("redirect:/user");
}else{
mv.setViewName("useradd");
}
//}
return mv;
}
示例12: uploadFile
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的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;
}
示例13: registerMember
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
@Transactional
@Override
public void registerMember(Member vo, HttpServletRequest request) throws Exception {
// 비밀번호 암호화
String encodedPassword = passwordEncoder.encode(vo.getPassword());
vo.setPassword(encodedPassword);
// 파일 업로드 로직을 추가
HttpSession session = request.getSession();
MultipartFile mFile = vo.getUploadFile();
System.out.println(mFile.getSize() + "============" + mFile.isEmpty());
if (mFile.isEmpty() == false) { // 파일 업로드를 했다면
String fileName = mFile.getOriginalFilename();
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYYMMddHHmmssSSS");
String now = df.format(today);
String newfilename = now + "_" + fileName;
vo.setImgProfile(newfilename); // vo의 완벽한 세팅이 완료
String root = session.getServletContext().getRealPath("/");
String path = root + "\\resources\\upload\\";
File copyFile = new File(path + newfilename);
mFile.transferTo(copyFile); // upload 폴더에 newfilename이 저장
} else {
String defaultImg = "defaultUser.svg";
vo.setImgProfile(defaultImg);
}
memberDAO.registerMember(vo);
// 권한등록
authoritiesDAO.insertAuthority(new Authority(vo.getUserId(), Constants.ROLE_MEMBER));
}
示例14: storeIOc
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
private String storeIOc(HttpServletRequest request, MultipartFile file) {
String result = "";
String realPath = request.getSession().getServletContext().getRealPath("uploads");
if (file == null) {
return null;
}
String fileName = "";
String logImageName = "";
if (file.isEmpty()) {
result = "文件未上传";
} else {
String _fileName = file.getOriginalFilename();
String suffix = _fileName.substring(_fileName.lastIndexOf("."));
if(StringUtils.isNotBlank(suffix)){
if(suffix.equalsIgnoreCase(".xls") || suffix.equalsIgnoreCase(".xlsx") || suffix.equalsIgnoreCase(".txt")|| suffix.equalsIgnoreCase(".png")
|| suffix.equalsIgnoreCase(".doc") || suffix.equalsIgnoreCase(".docx") || suffix.equalsIgnoreCase(".pdf")
|| suffix.equalsIgnoreCase(".ppt") || suffix.equalsIgnoreCase(".pptx")|| suffix.equalsIgnoreCase(".gif")
|| suffix.equalsIgnoreCase(".jpg")|| suffix.equalsIgnoreCase(".jpeg")|| suffix.equalsIgnoreCase(".bmp")){
// /**使用UUID生成文件名称**/
logImageName = UUID.randomUUID().toString() + suffix;
fileName = realPath + File.separator + ATTACH_SAVE_PATH + File.separator + logImageName;
File restore = new File(fileName);
try {
file.transferTo(restore);
result = "/uploads/attach/" + logImageName;
} catch (Exception e) {
throw new RuntimeException(e);
}
}else{
result = "文件格式不对,只能上传ppt、ptx、doc、docx、xls、xlsx、pdf、png、jpg、jpeg、gif、bmp格式";
}
}
}
return result;
}
示例15: transferSpringRequestStreamToHD
import org.springframework.web.multipart.MultipartFile; //导入方法依赖的package包/类
protected FResult<String> transferSpringRequestStreamToHD(UploadRequest uploadRequest, String saveTempFileDirectory,
HttpServletRequest request) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMaps = multiRequest.getFileMap();
if (fileMaps != null && fileMaps.size() == 1) {
for (Entry<String, MultipartFile> fileEntry : fileMaps.entrySet()) {
if (fileEntry != null && !fileEntry.getValue().isEmpty()) {
// 得到本次上传文件
MultipartFile multiFile = fileEntry.getValue();
String originalFilename = multiFile.getOriginalFilename();
uploadRequest.setOriginalExtName(FilenameUtils.getExtension(originalFilename));
String fileName = UUID.randomUUID().toString() + "." + uploadRequest.getOriginalExtName();
if (StringUtils.isBlank(uploadRequest.getOriginalFilename())) {
uploadRequest.setOriginalFilename(fileName);
} else {
uploadRequest.setOriginalFilename(originalFilename);
}
String fileFullPath = saveTempFileDirectory + File.separator + fileName;
log.debug("file temp path : " + fileFullPath);
// 构造临时文件
File uploadTempFile = new File(fileFullPath);
try {
// 临时文件持久化到硬盘
multiFile.transferTo(uploadTempFile);
uploadRequest.setTemporaryFilePath(fileFullPath);
uploadRequest.setTemporaryFileSize(uploadTempFile.length());
} catch (IllegalStateException | IOException e) {
log.error("上传文件持久化到服务器失败,计划持久化文件 ", e);
return FResult.newFailure(HttpResponseCode.SERVER_IO_ERROR, "上传文件持久化到服务器失败");
}
}
}
return FResult.newSuccess("上传成功");
} else {
return FResult.newFailure(HttpResponseCode.CLIENT_PARAM_INVALID, "一次请求仅支持上传一个文件");
}
}