SpringBoot+Vue文件上传+浏览

该文章详细描述了一个使用SpringMVC创建的RESTfulAPI,处理前端上传的PDF文件,包括文件类型验证、存储路径生成和URL返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后端:

package cn.ljy.supplies.controller;


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

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    @PostMapping("upload")
    public Map<String, Object> fileupload(MultipartFile file, HttpServletRequest req) {
        Map<String,Object> result = new HashMap<>();
        String originName = file.getOriginalFilename();
        if (!originName.endsWith(".pdf")) {
            result.put("status","error");
            result.put("asg","文件类型不对");
            return result;
        }
        String format = sdf.format(new Date());
        String realPath = req.getServletContext().getRealPath("/") +format;
        File folder = new File(realPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String newName = UUID.randomUUID().toString() + ".pdf";
        try {
            file.transferTo(new File(folder,newName));
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;
            result.put("status","success");
            result.put("url",url);
        } catch (IOException e) {
            result.put("status","error");
            result.put("asg",e.getMessage());
        }
        return result;
    }
}

前端:

<template>
  <div>
    <el-upload
            class="upload-demo"
            action=" http://localhost:8080/upload"
            :on-success="onSuccess"
            :on-preview="handlePreview"
            accept=".pdf"
            :limit="10">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
  </div>
</template>

<script>
export default {
    methods: {
            onSuccess(response, file, fileList) {
                console.log(response);
                console.log(file);
                console.log(fileList);
            },
            handlePreview(file) {
                console.log(file)
                console.log(file.response.url);
                window.open(file.response.url);
            }
        }

}
</script>

<style>

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值