Web应用,使用MultipartFile 类和File 类上传文件

1、上传图片源码

import com.ppmall.common.ServerResponse;
import com.ppmall.dao.AdvertMapper;
import com.ppmall.pojo.Advert;
import com.ppmall.service.IFileService;
import com.ppmall.util.FtpUtil;
import com.ppmall.util.PropertiesUtil;
import com.ppmall.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("iFileService")
public class FileServiceImpl implements IFileService {

    @Autowired
    private AdvertMapper advertMapper;

    //上传文件
    @Override
    public ServerResponse uploadFile(MultipartFile file, String path) throws IOException {
		
		//如果文件夹不存在则创建文件夹
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }

        //得到文件名
        String fileName = file.getOriginalFilename();
        //把文件名封装一下
        fileName = UUIDUtil.getUUID() + fileName.substring(fileName.lastIndexOf("."));


        // PropertiesUtil只是一个从配置文件得到字符串的工具类,得到
        String fileUrl = PropertiesUtil.getProperty("ftp.server.http.prefix") + fileName;          //   这里工具类得到的是 /upload/字符串
        //创建file对象
        File targetfile = new File(path+File.separator+fileName);
        //将数据传送到指定file对象中,也就是存储图片,targetfile包含了路径和文件名的
        file.transferTo(targetfile);

        // 用returnMap封装返回数据
        Map returnMap = new HashMap();
        returnMap.put("uri",fileName);
        //returnMap.put("url",fileUrl);
        returnMap.put("file_path",fileUrl);

        // Advert 为entety,把数据出入到数据库中
        Advert advert = new Advert();
        advert.setImage(fileUrl);
        advertMapper.insertSelective(advert);

        return ServerResponse.createSuccess("上传成功",returnMap);
    }
}

2、SSM框架中,图片存储的位置

  • path为下面的这个值
// 这里得到的path的值为 D:\软件\学习软件\IDEA2020\work_space\酒店管理\target\ppmall\upload
String path = session.getServletContext().getRealPath("upload");

在这里插入图片描述

3、其他

  • 前端读取文件
    在这里插入图片描述
  • webapp文件夹和target文件夹
    在这里插入图片描述
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值