java的文件上传

在此一共列举4版文件上传的代码:
第一版,上传后生成浏览器路径,访问该路径即可查看图片:
静态配置过得HTML可以直接链接后端:

单文件上传 上传文件代码: 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.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 "失败";
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值