//单个文件上传
@RequestMapping( value ="/testUploadFile" ,method=RequestMethod.POST)
public void testUploadFile(HttpServletRequest request,MultipartHttpServletRequest multipartHttpServletRequest){
//获取文件的路径
String uploadPath=multipartHttpServletRequest.getFile("file1").getOriginalFilename();
System.out.println("获取到的文件上传的路径是:"+uploadPath);
//截取文件上传的名称
String fileName = uploadPath.substring(uploadPath.lastIndexOf('\\') + 1, uploadPath.indexOf('.'));
System.out.println("获取到上传文件的名称是:"+fileName);
//获取上传文件的后缀
String fileSuffix = uploadPath.substring(uploadPath.indexOf(".")+1,uploadPath.length());
System.out.println("获取到的文件的后缀是:"+fileSuffix);
//文件输出流
FileOutputStream outputStream = null;
//文件输入流
FileInputStream inputStream = null;
//获取文件输入了
try {
inputStream = (FileInputStream) multipartHttpServletRequest.getFile("file1").getInputStream();
//指定上传后的文件存放的路径
outputStream = new FileOutputStream(new File("C://imagF//"+fileName+"."+fileSuffix));
byte [] temp =new byte[1024];
int i = inputStream.read(temp);
while(i != -1){
outputStream.write(temp, 0, temp.length);
outputStream.flush();
i = inputStream.read(temp);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
postman测试:
多个文件上传:
//多文件上传
@RequestMapping(value = "/testUploadFiles", method = RequestMethod.POST)
public void testUploadFiles(HttpServletRequest request,MultipartHttpServletRequest multipartHttpServletRequest){
//获取上传文件集合
List<MultipartFile> files = multipartHttpServletRequest.getFiles("files");
MultipartFile file = null;
BufferedOutputStream stream = null;
//遍历文件集合
for(int i = 0; i< files.size() ; ++i){
file = files.get(i);
//判断获取到的文件是否为空
if(!file.isEmpty()){
//获取文件的上传路径
String uploadPath=file.getOriginalFilename();
System.out.println("获取到的文件上传的路径是:"+uploadPath);
//截取文件上传的名称
String fileName = uploadPath.substring(uploadPath.lastIndexOf('\\') + 1, uploadPath.indexOf('.'));
System.out.println("获取到上传文件的名称是:"+fileName);
//获取上传文件的后缀
String fileSuffix = uploadPath.substring(uploadPath.indexOf(".")+1,uploadPath.length());
System.out.println("获取到的文件的后缀是:"+fileSuffix);
//指定上传后文件存放的位置
try {
stream = new BufferedOutputStream(new FileOutputStream(new File("C://imagF//"+fileName+"."+fileSuffix)));
byte[] bytes = file.getBytes();
stream.write(bytes,0,bytes.length);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(stream != null){
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("上传的文件为空!");
}
}
}
}
System.out.println("文件接受成功了");
}
postman测试:
网友评论