您的位置:首页 > 编程语言

简单的文件上传后台代码

2020-02-01 20:35 78 查看

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;

/**

  • Created by dell on 2019/8/1.
    */
    @Controller
    @RequestMapping(“test”)
    public class uploading {
    @RequestMapping(“upload”)
    public void importExcel(HttpServletRequest request, Map<String, Object> map, Integer t) {

    uploadFile(request,"");//文件上传

    }

    public static void uploadFile(HttpServletRequest req, String url){

    MultipartHttpServletRequest multi = (MultipartHttpServletRequest) req;
    MultipartFile file = multi.getFile("file");
    
    String fileName = file.getOriginalFilename();
    
    //String ff = fileName.substring(0, fileName.lastIndexOf("."));//文件名
    String fn = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//文件后缀
    
    String ft = fn.toUpperCase();
    
    String newFileName = UUID.randomUUID().toString() + "." + fn;
    
    url = "e:\\test";
    
    String uploadPath =  url;//文件上传位置
    
    //文件位置
    String filePath = uploadPath + newFileName;
    
    File fileSave = new File(uploadPath);
    fileSave.setWritable(true, false);
    if (!fileSave.exists()){
    fileSave.mkdirs();
    }
    
    try{
    InputStream in = file.getInputStream();
    OutputStream out = new FileOutputStream(filePath);//输出
    byte[] buffer = new byte[1024];//缓存
    int len = 0;
    
    while ((len = in.read(buffer)) > 0) {
    out.write(buffer, 0, len);
    }
    }catch (Exception e) {
    e.printStackTrace();
    }

    }
    }
    简单的文件上传后台代码

  • 点赞
  • 收藏
  • 分享
  • 文章举报
放牛的小牧童 发布了7 篇原创文章 · 获赞 0 · 访问量 155 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: