上传文件到服务器指定路径下

直接上完整代码

/**
 * 文件上传
 */
public class fileUpload {
    @Autowired
    ServletContext context;
    @Autowired
    private Upload_pubMapper upload_pubMapper;

    /**
     * 文件上传至服务器指定目录下
     * 文件信息(原始文件名、用id替换后的文件名、文件相对路径(地址)、后缀)存入附件表中
     * 返回文件id存入主表
     * 扩充:查询时用附件id关联附件表,返回文件名以及文件相对地址,即可满足前端页面点击下载的功能
     * @param request
     * @param response
     * @param id 主表id(为哪条数据上传文件)
     * @param file MultipartFile类型文件
     * @return map 返回上传成功标识
     * @throws Exception
     */
    public Map upload(HttpServletRequest request, HttpServletResponse response, String id,MultipartFile file)throws Exception {
        Map<String,String> map = new HashMap<String, String>();
        try {
            if (file != null && file.getOriginalFilename() != null && !file.getOriginalFilename().equals("")) {
                String fjid = SnowIdUtil.snowIdUtil.nextId();
                Upload_pubPage uploadPage = new Upload_pubPage(); // 附件表实体
                uploadPage.setId(fjid);
                String xsm=file.getOriginalFilename(); // 获取文件名(含后缀)
                String wjlx=xsm.substring(xsm.lastIndexOf(".")+1); // 获取文件后缀
                String ccm=uploadPage.getId()+"."+wjlx; // 更改文件名称,用id替代(防止重名)
                // 附件信息给附件表实体赋值
                uploadPage.setXsm(xsm);
                uploadPage.setCcm(ccm);
                uploadPage.setWjlx(wjlx);
                //保存的文件名
                String dFileName = uploadPage.getCcm();
                //保存路径
                //springboot 默认情况下只能加载 resource文件夹下静态资源文件
                //生成保存文件
                String savePath = "upload/pub/";
                String realPath = context.getRealPath("/");    //实际路径
                String dz = realPath + "/" + savePath + dFileName;
                File uploadFile = new File(dz);
                if (!uploadFile.exists()) {
                    uploadFile.getParentFile().mkdirs(); // 创建pub文件夹
                    uploadFile.createNewFile(); // 创建文件
                }
                file.transferTo(uploadFile); // 保存文件
                uploadPage.setWllj(savePath + uploadPage.getCcm()); // 文件的相对路径
                // 将附件信息存入附件表
                upload_pubMapper.uploadFirst(uploadPage);
                // 更新主表的附件id(此处省略)

                map.put("jg","1");
                map.put("message", "上传成功");
            } else {
                map.put("jg","-1");
                map.put("message", "上传失败,请选择文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("jg","-1");
            map.put("message", "上传失败"+e.getMessage());
        }
        return map;
    }
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值