首页 > 编程语言 >Java 文件上传

Java 文件上传

时间:2023-02-17 09:33:24浏览次数:57  
标签:文件 Java String filePath File file path new 上传

一:配置springBoot上传文件限制

spring:
  servlet:
    multipart:
      max-file-size: 100MB  #单个文件大小
      max-request-size: 1024MB #总文件大小

二:代码

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Locale;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadController {

    /**
     * 上传方式一,从请求体中获取文件信息
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("method1")
    public String upload1(HttpServletRequest request) throws IOException {

        MultipartFile file = ((StandardMultipartHttpServletRequest) request).getFile("file");
        String fileName = file.getOriginalFilename();
        String newName=UUID.randomUUID().toString()+fileName.substring(fileName.indexOf("."));

        // 获取当前操作系统
        String osName = System.getProperties().get("os.name").toString().toLowerCase(Locale.ROOT);
        String path="";

        if(osName.startsWith("win")){
            path="D:\\Test\\";
        }else{
            path="/mnt/test";
        }
        File saveFile=new File(path+newName);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
        }
        file.transferTo(saveFile);
        return saveFile.getPath();
    }

    /**
     * 上传方式2 MultipartFile 上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("method2")
    public String upload2(@RequestParam("file") MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String newName=UUID.randomUUID().toString()+fileName.substring(fileName.indexOf("."));
        // 获取当前操作系统
        String osName = System.getProperties().get("os.name").toString().toLowerCase(Locale.ROOT);
        String path="";

        if(osName.startsWith("win")){
            path="D:\\Test\\";
        }else{
            path="/mnt/test";
        }
        File saveFile=new File(path+newName);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
        }
        file.transferTo(saveFile);
        return saveFile.getPath();
    }

    /**
     * base64 图片上传
     * @param base64
     * @return
     */
    @PostMapping("method3")
    public String upload3(@RequestParam("base64")String base64){
        String base64Data = base64.split(",")[1];
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(base64Data);
        // 获取当前操作系统
        String osName = System.getProperties().get("os.name").toString().toLowerCase(Locale.ROOT);
        String path="";

        if(osName.startsWith("win")){
            path="D:\\Test\\";
        }else{
            path="/mnt/test";
        }
        String newName=UUID.randomUUID().toString()+".png";
        File saveFile=new File(path+newName);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(saveFile);
            fos.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return saveFile.getPath();
    }

    public static void main(String[] args) {
        String data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAFJklEQVR4Xu3VsRGAQAwEsaf/oqEBINj0RO7A8u9w3efcx0eAwKvAJRAvg8C3gEC8DgI/AgLxPAgIxBsg0AT8QZqbqREBgYwc2ppNQCDNzdSIgEBGDm3NJiCQ5mZqREAgI4e2ZhMQSHMzNSIgkJFDW7MJCKS5mRoREMjIoa3ZBATS3EyNCAhk5NDWbAICaW6mRgQEMnJoazYBgTQ3UyMCAhk5tDWbgECam6kRAYGMHNqaTUAgzc3UiIBARg5tzSYgkOZmakRAICOHtmYTEEhzMzUiIJCRQ1uzCQikuZkaERDIyKGt2QQE0txMjQgIZOTQ1mwCAmlupkYEBDJyaGs2AYE0N1MjAgIZObQ1m4BAmpupEQGBjBzamk1AIM3N1IiAQEYObc0mIJDmZmpEQCAjh7ZmExBIczM1IiCQkUNbswkIpLmZGhEQyMihrdkEBNLcTI0ICGTk0NZsAgJpbqZGBAQycmhrNgGBNDdTIwICGTm0NZuAQJqbqREBgYwc2ppNQC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N1MjAgIZObQ1m4BAmpupEQGBjBzamk1AIM3N1IiAQEYObc0mIJDmZmpEQCAjh7ZmExBIczM1IiCQkUNbswkIpLmZGhEQyMihrdkEBNLcTI0ICGTk0NZsAgJpbqZGBAQycmhrNgGBNDdTIwICGTm0NZuAQJqbqREBgYwc2ppNQCDNzdSIwAOn4Y9IyHT+ZAAAAABJRU5ErkJggg==";
    }
}

通过文件地址上传文件

 

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();
        }
    }

 





标签:文件,Java,String,filePath,File,file,path,new,上传
From: https://www.cnblogs.com/xiaotian0422/p/17129024.html

相关文章