使用 JAVA 文件上传的几种方法
最编程
2024-06-23 11:45:50
...
文章目录
- 通过文件地址上传文件
- 通过文件传入并存放服务器
- 上传并生成随即名
- 以base64编码上传文件
- 上传附件的接口如下
通过文件地址上传文件
1、webUtil工具类下载图片如下
public static void downloadImgByNet(String ServerfilePath,String filePath,String fileName){
try{
URL url = new URL(ServerfilePath);
URLConnection conn = url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//输出流
InputStream str = conn.getInputStream();
//控制流的大小为1k
byte[] bs = new byte[1024];
//读取到的长度
int len = 0;
//是否需要创建文件夹
File saveDir = new File(filePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+ File.separator+fileName);
//实例输出一个对象
FileOutputStream out = new FileOutputStream(file);
//循环判断,如果读取的个数b为空了,则is.read()方法返回-1,具体请参考InputStream的read();
while ((len = str.read(bs)) != -1) {
//将对象写入到对应的文件中
out.write(bs, 0, len);
}
//刷新流
out.flush();
//关闭流
out.close();
str.close();
System.out.println("下载成功");
}catch (Exception e) {
e.printStackTrace();
}
}
** 2、上传图片接口**
@Value("${uploadfile.fileLoadPath}")
String fileLoadPath="E:\\test";
@RequestMapping(method = RequestMethod.POST, value = "/fileUpload")
public void ChangeState(@RequestBody Map param, HttpServletRequest request,
HttpServletResponse response){
String UploadfilePath="";
if (param.get("UploadfilePath")!=null){
UploadfilePath=param.get("UploadfilePath").toString();
}
String fileName="";
if (param.get("fileName")!=null){
fileName=param.get("fileName").toString();
}
WebUtil.downloadImgByNet(UploadfilePath,fileLoadPath,fileName);
}
通过文件传入并存放服务器
@Value("${uploadfile.fileLoadPath}")
String fileLoadPath="E:\\test";
/**
* 文件的上传
* @param file
* @return
*/
@RequestMapping(value = "/uploads",method = RequestMethod.POST)
public void upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
// 判断文件是否为空
String path = fileLoadPath;
HashMap<String, String> message = new HashMap<>();
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = path + "/" + file.getOriginalFilename();
if (!new File(filePath).exists()){
new File(filePath).mkdirs();
}
// 转存文件
file.transferTo(new File(filePath));
message.put("status", filePath);
} catch (Exception e) {
// e.printStackTrace();
message.put("status", "error");
}
}
renderResult(response, message);
}
上传并生成随即名
@Value("${uploadfile.fileLoadPath}")
String fileLoadPath="E:\\test";
/**
* 文件的上传
* @param file
* @return
*/
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public void upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
// 判断文件是否为空
String path = fileLoadPath;
HashMap<String, String> message = new HashMap<>();
if (!file.isEmpty()) {
try {
// 文件保存路径
// String filePath = path + "/" + file.getOriginalFilename();
String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //获取文件的后缀名
String filePath = path+"\\"+UUID.randomUUID().toString().replace("-","")+suffixName; //拼接
if (!new File(filePath).exists()){
new File(filePath).mkdirs();
}
// 转存文件
file.transferTo(new File(filePath));
message.put("status", filePath);
} catch (Exception e) {
// e.printStackTrace();
message.put("status", "error");
}
}
renderResult(response, message);
}
以base64编码上传文件
以下为base64的编码和解码的工具类
public class FileBase64Utils {
/**
* 本地文件(图片、excel等)转换成Base64字符串
*
* @param file 接受的文件
*/
public static String convertFileToBase64(MultipartFile file) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = file.getInputStream();
// InputStream in = new FileInputStream(imgPath);
System.out.println("文件大小(字节)=" + in.available());
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组进行Base64编码,得到Base64编码的字符串
Base64.Decoder decoder = Base64.getDecoder();
Base64.Encoder encoder = Base64.getEncoder();
String base64Str = encoder.encodeToString(data);
return base64Str;
}
/**
* 将base64字符串,生成文件
*/
public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
Base64.Decoder decoder = Base64.getDecoder();
Base64.Encoder encoder = Base64.getEncoder();
// BASE64Decoder decoder = new BASE64Decoder();
byte[] bfile = decoder.decode(fileBase64String);
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
上传附件的接口如下
/**
* 附件上传接口
* @param request
* @param response
* @param file 前端传来的附件
*/
@RequestMapping(method = RequestMethod.POST, value = "/uploadFile")
public void uploadFile(HttpServletRequest request,
HttpServletResponse response, MultipartFile file){
Map<String,Object> res = new HashMap<String, Object>();
try{
long start = System.currentTimeMillis(); //获取开始的时间
String filename = file.getOriginalFilename(); //获取文件名
String imgBase64Str = FileBase64Utils.convertFileToBase64(file); //使用base64对文件编码成字符串格式
System.out.println("Base64字符串length=" + imgBase64Str.length()); //得到编码后的长度
// 如果文件不存在,则创建
if (!new File(ServerloadPath).exists()){
new File(ServerloadPath).mkdirs();
}
// 重新将字符串解码为文件类型并上传
File file1 = FileBase64Utils.convertBase64ToFile(imgBase64Str, ServerloadPath, filename);
assert file1 != null;
String absolutePath = file1.getAbsolutePath();
// 输入花费时间
System.out.println("duration:" + (System.currentTimeMillis() - start));
// 返回存放地址
res.put("filePath", absolutePath);
res.put("duration",System.currentTimeMillis() - start+"ms");
renderResult(response, res);
}catch(Exception ex){
ex.printStackTrace();
}
}
如有不对的地方,欢迎指点
推荐阅读
-
在Linux系统下安装和使用软件解压RAR文件的方法
-
Java 8新特性探究(十三)JavaFX 8新特性以及开发2048游戏-JavaFX历史## 跟java在服务器端和web端成绩相比,桌面一直是java的软肋,于是Sun公司在2008年推出JavaFX,弥补桌面软件的缺陷,请看下图JavaFX一路走过来的改进 从上图看出,一开始推出时候,开发者需使用一种名为JavaFX Script的静态的、声明式的编程语言来开发JavaFX应用程序。因为JavaFX Script将会被编译为Java bytecode,程序员可以使用Java代码代替。 JavaFX 2.0之后的版本摒弃了JavaFX Script语言,而作为一个Java API来使用。因此使用JavaFX平台实现的应用程序将直接通过标准Java代码来实现。 JavaFX 2.0 包含非常丰富的 UI 控件、图形和多媒体特性用于简化可视化应用的开发,WebView可直接在应用中嵌入网页;另外 2.0 版本允许使用 FXML 进行 UI 定义,这是一个脚本化基于 XML 的标识语言。 从JDK 7u6开始,JavaFx就与JDK捆绑在一起了,JavaFX团队称,下一个版本将是8.0,目前所有的工作都已经围绕8.0库进行。这是因为JavaFX将捆绑在Java 8中,因此该团队决定跳过几个版本号,迎头赶上Java 8。 ##JavaFx8的新特性 ## ###全新现代主题:Modena 新的Modena主题来替换原来的Caspian主题。不过在Application的start方法中,可以通过setUserAgentStylesheet(STYLESHEET_CASPIAN)来继续使用Caspian主题。 参考http://fxexperience.com/2013/03/modena-theme-update/ ###JavaFX 3D 在JavaFX8中提供了3D图像处理API,包括Shape3D (Box, Cylinder, MeshView, Sphere子类),SubScene, Material, PickResult, LightBase (AmbientLight 和PointLight子类),SceneAntialiasing等。Camera类也得到了更新。从JavaDoc中可以找到更多信息。 ###富文本 强化了富文本的支持 ###TreeTableView ###日期控件DatePicker 增加日期控件 ###用于 CSS 结构的公共 API
-
将点云文件转换为网格模型的方法——使用Meshlab
-
Unity中的bvh文件使用方法指南
-
恢复Linux文件误删除的操作方法:使用debugfs进行恢复
-
将本地图片上传至数据库的Java获取方法
-
使用apktool和java_apktool进行APK反编译的方法
-
在JSP中使用JavaScript获取Java变量的值和对象的方法
-
在JSP中使用Java获取页面变量及其对象属性的方法
-
在JSP中使用Java遍历JSON数据的循环方法