Springboot(九).多文件上传下载文件(并将url存入数据库表中)

一.   文件上传

这里我们使用request.getSession().getServletContext().getRealPath("/static")的方式来设置文件的存储路径,并存入数据库中

request.getSession().getServletContext() 获取的是Servlet容器对象,相当于tomcat容器了。getRealPath("/") 获取实际路径,“/”指代项目根目录,所以代码返回的是项目在容器中的实际发布运行的根路径

这里我的文件就保存在了tomcat容器:C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.4580300150688111201.8080\static下

当我们部署到linux的时候,文件就保存在了/tmp/tomcat-docbase.6117940652560190565.8088/static/下

Controller:

/**
 *  多文件上传接口
 * */
@ResponseBody
@RequestMapping(value = "/fileUpload", produces = "application/json;charset=UTF-8")
public JSONObject fileUpload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws Exception{
    String serverName = "文件上传";
    VirgoLog.updateStep(CONTROLLER_NAME_DES,serverName);
    List<FileManage> fileManages = fileService.fileUpload(files,request);
    Map<String,Object> resMap = new HashMap<String,Object>();
    //0:操作成功
    resMap.put("code", ErrorCode.ERR_SUCCEED.getErrorCode());
    resMap.put("desc",ErrorCode.ERR_SUCCEED.getErrorMessage());
    resMap.put("fileInfo",fileManages);
    return JSON.parseObject(JSONConvertor.toJSON(resMap));
}

service  文件上传业务类

/**
     * 文件上传service
     * @param files
     * @throws Exception
     */
    @Override
    public void fileUpload(@RequestParam("file")MultipartFile[] files, HttpServletRequest request) throws Exception {
        //文件命名
        //保存时的文件名
        for(int i=0;i<files.length;i++) {
            //保存文件到本地文件,并保存路径到数据库
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar calendar = Calendar.getInstance();
            String fileName = df.format(calendar.getTime()) + files[i].getOriginalFilename();
            log.log("文件的文件名为:" + fileName);
            //保存文件的绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("static/");
            log.log("文件的绝对路径:" + filePath);
            FileManage fileManage = new FileManage();
            try {
                //上传文件
                FileUtil.uploadFile(files[i].getBytes(), filePath, fileName);
                //保存到数据库代码,存入路径以及文件名称
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                throw new ZDYException(ErrorCode.ERR_FILE_UPLOAD_FAIL);
            }
        }
            }

  

文件上传工具类

/**
 * Created by hengyang4 on 2018/11/2.
 */
public class FileUtil {

    //文件上传工具类服务方法
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception{

        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

}

二.    文件下载

/**
 * 文件下载service
 * @param fileId
 * @throws Exception
 */
@Override
public String downloadFile(String fileId, HttpServletResponse response) throws Exception {
    //这里要根据文件id在数据库中查询之前保存的文件信息    FileManage fileManage = fileManageMapper.selectByPrimaryKey(fileId);
    //文件名
    String fileName = fileManage.getFileName();
    //文件的相对路径
    String path = fileManage.getFilePath();
    InputStream inputStream = new FileInputStream(new File(path + fileName));
    //如果文件不存在
    if(inputStream == null){
        throw new ZDYException(ErrorCode.ERR_NOT_FILE);
    }
    response.setHeader("content-type", "application/octet-stream");
    response.setContentType("application/octet-stream");
    try {
        String name = java.net.URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + name );
    } catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
    }
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
    try {
        os = response.getOutputStream();
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            os.write(buff, 0, buff.length);
            os.flush();
            i = bis.read(buff);
        }
    } catch (FileNotFoundException e1) {
        //e1.getMessage()+"系统找不到指定的文件";
        throw new ZDYException(ErrorCode.ERR_NOT_FILE);
    }catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return "success";

}

  这就是springboot中文件的上传和下载,很简单很快捷

posted @ 2018-11-13 16:13 袋?饲养员 阅读(...) 评论(...) 编辑 收藏

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现前端上传文件到本地并将url存入本地数据库,需要前后端协同完成以下几个步骤: 1. 前端使用 Vue.js 实现文件上传,并将文件传递给后端。 2. 后端使用 Spring Boot 接收前端传递的文件,并将文件保存到本地。 3. 后端生成本地文件URL,将URL保存到数据库。 4. 前端从数据库获取URL,展示文件信息。 以下是具体实现步骤: 1. 前端实现文件上传,使用 Vue.js 和 Axios 实现,代码如下: ```html <template> <div> <input type="file" @change="onFileChange"> <button @click="uploadFile">上传</button> </div> </template> <script> import axios from 'axios'; export default { data() { return { file: null }; }, methods: { onFileChange(event) { this.file = event.target.files[0]; }, uploadFile() { const formData = new FormData(); formData.append('file', this.file); axios.post('/api/upload', formData).then(response => { console.log(response.data); }).catch(error => { console.log(error); }); } } }; </script> ``` 2. 后端使用 Spring Boot 接收前端传递的文件,并将文件保存到本地。代码如下: ```java @RestController @RequestMapping("/api") public class FileController { @Value("${file.upload-dir}") private String uploadDir; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { String filename = file.getOriginalFilename(); Path path = Paths.get(uploadDir, filename); Files.write(path, file.getBytes()); return "上传成功"; } } ``` 在 Spring Boot ,使用 `@Value` 注解获取配置文件的变量值,即上传文件存储的路径。 3. 后端生成本地文件URL,将URL保存到数据库。代码如下: ```java @RestController @RequestMapping("/api") public class FileController { @Autowired private FileRepository fileRepository; @Value("${file.base-url}") private String baseUrl; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { String filename = file.getOriginalFilename(); Path path = Paths.get(uploadDir, filename); Files.write(path, file.getBytes()); String url = baseUrl + filename; fileRepository.save(new FileEntity(filename, url)); return "上传成功"; } } ``` 在 Spring Boot ,使用 `@Value` 注解获取配置文件的变量值,即本地文件URL前缀。 4. 前端从数据库获取URL,展示文件信息。代码如下: ```html <template> <div> <div v-for="file in files" :key="file.id"> <a :href="file.url">{{ file.name }}</a> </div> </div> </template> <script> import axios from 'axios'; export default { data() { return { files: [] }; }, mounted() { axios.get('/api/files').then(response => { this.files = response.data; }).catch(error => { console.log(error); }); } }; </script> ``` 在 Vue.js ,使用 `axios` 发送请求获取文件信息,展示文件的名称和URL。需要注意的是,文件URL需要使用 `<a>` 标签展示,并且需要设置 `href` 属性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值