单文件个多文件上传

package com.qlzx.utils;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
/**

  • 可以用
  • 单文件和多文件的上传
  • @author Liang Qizhao

*/
@Controller
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//文件上传相关代码
@RequestMapping(value = “upload”)
@ResponseBody
public String upload(@RequestParam(“test”) MultipartFile file) {
if (file.isEmpty()) {
return “文件为空”;
}
// 获取文件名
String fileName = file.getOriginalFilename();
logger.info(“上传的文件名为:” + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info(“上传的后缀名为:” + suffixName);
// 文件上传后的路径
String filePath = “E://test//”;
// 解决中文问题,liunx下中文路径,图片显示问题
// fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return “上传成功”;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return “上传失败”;
}

//多文件上传
@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(HttpServletRequest request) {
	List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
	MultipartFile file = null;
	BufferedOutputStream stream = null;
	

	
	for (int i = 0; i < files.size(); ++i) {
		file = files.get(i);
		if (!file.isEmpty()) {
			try {
			    // 检测是否存在目录
				 String filePath = "E://test//"+file.getOriginalFilename();
				 File dest=new File(filePath);
		        if (!dest.getParentFile().exists()) {
		            dest.getParentFile().mkdirs();
		        }
				byte[] bytes = file.getBytes();
				File file2 = new File(file.getOriginalFilename());
				stream = new BufferedOutputStream(new FileOutputStream(dest));
				stream.write(bytes);
				stream.close();

			} catch (Exception e) {
				stream = null;
				return "上传失败"+e.getMessage();
			}
		} else {
			return "文件为空";
		}
	}
	return "上传成功";
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值