在此一共列举4版文件上传的代码:
第一版,上传后生成浏览器路径,访问该路径即可查看图片:
静态配置过得HTML可以直接链接后端:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
public class FileUploadController {
SimpleDateFormat sdf=new SimpleDateFormat(“yyyy/MM/dd/”);
@PostMapping("/upload")
public String upload(MultipartFile uploadFile, HttpServletRequest request){
//获得服务器的绝对路径
String realPath =request.getSession().getServletContext().getRealPath("/uploadFile");
System.out.println(“realPath:”+realPath);
//获取当前时间
String format =sdf.format(new Date());
System.out.println(“时间”+format);
//对 绝对路径和当前时间拼接为文件对象
File f = new File(realPath+format);
System.out.println(“文件名称”+f.getName());
//isDirectory判断 f是否是个目录,如果是个目录就返回true
if(!f.isDirectory()){
f.mkdirs();//mkdirs()可以在不存在的目录中创建文件夹。诸如:a\b,既可以创建多级目录。
}
//获取页面上传的文件名
String oldName=uploadFile.getOriginalFilename();
System.out.println(“旧文件名称”+oldName);
//新的文件名称,uuid加上旧文件名称加上就文件名字
String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
try {
//上传文件
uploadFile.transferTo(new File(f,newName));//该操作位
//生成的文件路径request.getScheme() 返回当前链接使用的协议,返回服务器的名
//request.getServerName()获取网站的域名
//request.getServerport()获取服务器端口号
//时间和新文件名称
String filePath=request.getScheme()+"?/"+request.getServerName()+":"+request.getServerPort()+"/uploadFile"+format+newName;
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
第二种,用流代替, uploadFile.transferTo(new File(f,newName)); 这一步操作
package com.vperson.fbz.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
public class MyFileUploadController {
SimpleDateFormat sdf=new SimpleDateFormat(“yyyy/MM/dd/”);
@PostMapping("/upload1")
public String upload(MultipartFile uploadFile, HttpServletRequest request){
//获得服务器的绝对路径
String realPath =request.getSession().getServletContext().getRealPath("/uploadFile");
System.out.println(“realPath:”+realPath);
//获取当前时间
String format =sdf.format(new Date());
System.out.println(“时间”+format);
//对 绝对路径和当前时间拼接为文件对象
File f = new File(realPath+format);
System.out.println(“文件名称”+f.getName());
//isDirectory判断 f是否是个目录,如果是个目录就返回true
if(!f.isDirectory()){
f.mkdirs();//mkdirs()可以在不存在的目录中创建文件夹。诸如:a\b,既可以创建多级目录。
}
//获取页面上传的源文件名称
String oldName=uploadFile.getOriginalFilename();
System.out.println("旧文件名称"+oldName);
//新的文件名称,uuid加上旧文件名称加上就文件名字
String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
int len ;
byte[] bytes =new byte[1024];
//int len;
try {
//上传文件
//uploadFile.transferTo(new File(f,newName));//该操作位
InputStream reader = uploadFile.getInputStream();
OutputStream writer = new FileOutputStream(newName);
while((len=reader.read(bytes)) !=-1){
writer.write(bytes,0,len);
}
//生成的文件路径request.getScheme() 返回当前链接使用的协议,返回服务器的名
//request.getServerName()获取网站的域名
//request.getServerport()获取服务器端口号
//时间和新文件名称
String filePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/uploadFile"+format+newName;
reader.close();
writer.close();
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
第三种,自己写工具类,调用
工具类:
package com.vperson.fbz.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
public class IoUtil {
public static String insert(MultipartFile oldFile, File newFile){
try {
if(!(newFile.getParentFile().isDirectory())){
//创造父目录,也就是文件夹
newFile.getParentFile().mkdirs();
//创造文件
newFile.createNewFile();
byte[] bytes = new byte[1024];
int len = 0;
//创建流
InputStream fileInputStream =oldFile.getInputStream();
OutputStream fileOutputStream =new FileOutputStream(newFile);
while((len=fileInputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
}
return “上传成功”;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return “上传失败”;
}
}
调用:
@PostMapping(“fbz”)
public String upLoad(MultipartFile file){
String nf= “G:\javaee”+"\"+“io”+"\"+ UUID.randomUUID().toString()+"\"+file.getOriginalFilename();
File newFile = new File(nf);
return IoUtil.insert( file,newFile);
}
第四种,利用 HttpServletRequest接口里的getPart()获取文件并用Part接口的write放写
@PostMapping (“fbz11”)
public String upLoad1( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding(“utf-8”);
response.setCharacterEncoding(“utf-8”);
Part file = request.getPart(“file123”);
String path = request.getServletContext().getRealPath("/");
System.out.println(“环境”+path);
System.out.println(“文件名”+file.getSubmittedFileName());
System.out.println(“大小”+file.getSize());
System.out.println(“表单名”+file.getName());
String nf= "G:\\javaee"+"\\"+"io"+"\\"+ UUID.randomUUID().toString()+"\\"+file.getSubmittedFileName();
System.out.println(2);
File newFile = new File(nf);
System.out.println(3);
int len=0;
if(!newFile.getParentFile().isDirectory()) {
newFile.getParentFile().mkdirs();
newFile.createNewFile();
file.write(newFile.getAbsolutePath());
System.out.println(5);
return "成功";
}
return "失败";
}
本文详细介绍四种不同的文件上传代码实现方式,包括直接生成浏览器访问路径、使用流替代transferTo方法、自定义工具类进行文件操作及利用HttpServletRequest的getPart方法进行文件处理。每种方法都提供了具体代码示例,便于读者理解和应用。
7008

被折叠的 条评论
为什么被折叠?



