Springboot+fileinput图片上传,bootstrap前端+java后端

前言

这段时间空余时间研究了一下图片上传,使用fileinput插件,网上的例子只有前端提交上传,没有后端接收和处理图片,最后我成功实现以后我想把他记录下来,好记性不如烂笔头,先给大家看看效果:

1、一个简单的主界面,bootstrap做的,freemarker做界面数据渲染,实现了分页,批删,修改,删除,添加的功能,图片上传用在添加和修改中,主界面如下图:

 当我点击添加按钮跳转到新增界面:

先上传,再提交,即可;

2、实现的步骤:导入fileinput的js和css自己解决

前端代码:

<div class="form-group">
        <label class="col-sm-2 control-label">图片上传</label>
        <div class="col-sm-4">
            <input id="input-file" name="file" multiple type="file" data-show- 
             caption="true">             
        </div>
</div>
// 文件上传
    $(function () {
        initFileInput("input-file");
    })

    function initFileInput(ctrlName) {
        var imags = new Array();
        var control = $('#' + ctrlName);
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: "/commodity/uploads", //上传的地址
            allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
            //uploadExtraData:{"id": 1, "fileName":'123.mp3'},
            uploadAsync: true, //默认异步上传
            showUpload: true, //是否显示上传按钮
            showRemove : true, //显示移除按钮
            showPreview : true, //是否显示预览
            showCaption: false,//是否显示标题
            browseClass: "btn btn-primary", //按钮样式
            //dropZoneEnabled: true,//是否显示拖拽区域
            //minImageWidth: 50, //图片的最小宽度
            //minImageHeight: 50,//图片的最小高度
            //maxImageWidth: 1000,//图片的最大宽度
            //maxImageHeight: 1000,//图片的最大高度
            //maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
            //minFileCount: 0,
            //maxFileCount: 10, //表示允许同时上传的最大文件个数
            enctype: 'multipart/form-data',
            validateInitialCount:true,
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",

        }).on('filepreupload', function(event, data, previewId, index) {     //上传中
            var form = data.form, files = data.files, extra = data.extra,
                response = data.response, reader = data.reader;
            console.log('文件正在上传');
        }).on("fileuploaded", function (event, data, previewId, index) {    //一个文件上传成功
            var response = data.response;
            //alert(response.filePath);
            imags.push(response.filePath)
            $("#images").val(imags);
            console.log('文件上传成功!'+data.id);

        }).on('fileerror', function(event, data, msg) {  //一个文件上传失败
            console.log('文件上传失败!'+data.id);


        })
    }

后端controller实现:

/**
     * 文件上传
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/uploads",method = RequestMethod.POST)
    public Map<String,Object> uploads(MultipartFile file,HttpServletRequest request) throws Exception{
        Map<String, Object> map = new HashMap();
        File targetFile=null;
        //返回存储路径
        String filePath="";
        int code=1;
        System.out.println(file);
        //获取文件名加后缀
        String fileName = file.getOriginalFilename();
        if(fileName != null && fileName != ""){
            //图片访问的URI
            String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";
            //文件临时存储位置
            String path = request.getSession().getServletContext().getRealPath("") + "upload" + File.separator + "imgs";

            //文件后缀
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            //新的文件名
            fileName = System.currentTimeMillis()+"_"+new Random().nextInt(1000) + fileSuffix;

            //先判断文件是否存在
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileAdd = sdf.format(new Date());
            //获取文件夹路径
            path = path + File.separator + fileAdd + File.separator;
            File file1 =new File(path);
            //如果文件夹不存在则创建
            if(!file1 .exists()  && !file1 .isDirectory()){
                file1 .mkdirs();
            }
            //将图片存入文件夹
            targetFile = new File(file1, fileName);
            try {
                //将上传的文件写到服务器上指定的文件。
                file.transferTo(targetFile);
                String projectPath = System.getProperty("user.dir");
                //文件复制
                String src = path + fileName;
                //根据自己系统的resource 目录所在位置进行自行配置
                //E:\hhf\develop20190805\mall\src\main\resources
                String destDir = projectPath + File.separator+"src"+File.separator+"main"+ File.separator +"resources"+File.separator+"static"+ File.separator+"upload"+File.separator+"imgs" + File.separator + fileAdd + File.separator;
                copyFile(src,destDir,fileName);

                filePath= returnUrl + fileAdd + "/"+ fileName;
                code=0;
                map.put("filePath", filePath);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return map;
    }
/**
     * 复制文件
     * @param src
     * @param destDir
     * @param fileName
     * @throws IOException
     */
    public void copyFile(String src,String destDir,String fileName) throws IOException{
        FileInputStream in=new FileInputStream(src);
        File fileDir = new File(destDir);
        if(!fileDir.isDirectory()){
            fileDir.mkdirs();
        }
        File file = new File(fileDir,fileName);

        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream out=new FileOutputStream(file);
        int c;
        byte buffer[]=new byte[1024];
        while((c=in.read(buffer))!=-1){
            for(int i=0;i<c;i++){
                out.write(buffer[i]);
            }

        }
        in.close();
        out.close();
    }

注意:如果是多个文件,返回路径的时候,将路径添加到一个数组里边就行了,我就是这么实现的,点提交后把路径传到后台,插入数据库就行了,写的不是很详细,有不明白的地方可以留言交流,希望博友们支出不足的地方,感谢!

完整代码和数据库脚本下载地址:https://github.com/Huanghengfeng/PersonProject.git

 

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
首先,需要在后端编写一个用于接收上传文件的接口,可以使用SpringBoot框架自带的MultipartFile类来处理上传的文件。代码示例如下: ```java @RestController @RequestMapping("/api") public class FileUploadController { @Autowired private FaceDataRepository repository; @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResponseEntity.badRequest().body("Please select a file to upload"); } try { byte[] data = file.getBytes(); InputStream inputStream = new ByteArrayInputStream(data); BufferedImage image = ImageIO.read(inputStream); // 将人脸数据存储到MySQL数据库中 FaceData faceData = new FaceData(); faceData.setData(data); repository.save(faceData); return ResponseEntity.ok().body("File uploaded successfully"); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file"); } } } ``` 其中,FaceData是一个数据库实体类,用于存储人脸数据的信息,具体定义如下: ```java @Entity @Table(name = "face_data") public class FaceData { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Lob private byte[] data; // getter/setter 略 } ``` 然后,在前端编写一个文件上传组件,使用Vue框架可以使用vue-upload-component库,示例代码如下: ```html <template> <div> <input type="file" ref="fileInput" @change="uploadFile" /> </div> </template> <script> import VueUploadComponent from 'vue-upload-component' export default { components: { vueUploadComponent: VueUploadComponent }, methods: { async uploadFile() { const files = this.$refs.fileInput.files const formData = new FormData() formData.append('file', files[0]) try { await this.$http.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) alert('File uploaded successfully') } catch (e) { console.log(e) alert('Failed to upload file') } } } } </script> ``` 注意,需要在Vue组件中引入axios库,在main.js中添如下代码: ```javascript import axios from 'axios' Vue.prototype.$http = axios.create({ baseURL: 'http://localhost:8080' }) ``` 其中,baseURL为后端接口的地址。完整代码如下: FileUploadController.java ```java @RestController @RequestMapping("/api") public class FileUploadController { @Autowired private FaceDataRepository repository; @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResponseEntity.badRequest().body("Please select a file to upload"); } try { byte[] data = file.getBytes(); InputStream inputStream = new ByteArrayInputStream(data); BufferedImage image = ImageIO.read(inputStream); // 将人脸数据存储到MySQL数据库中 FaceData faceData = new FaceData(); faceData.setData(data); repository.save(faceData); return ResponseEntity.ok().body("File uploaded successfully"); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file"); } } } ``` FaceData.java ```java @Entity @Table(name = "face_data") public class FaceData { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Lob private byte[] data; // getter/setter 略 } ``` App.vue ```html <template> <div> <input type="file" ref="fileInput" @change="uploadFile" /> </div> </template> <script> import VueUploadComponent from 'vue-upload-component' export default { components: { vueUploadComponent: VueUploadComponent }, methods: { async uploadFile() { const files = this.$refs.fileInput.files const formData = new FormData() formData.append('file', files[0]) try { await this.$http.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) alert('File uploaded successfully') } catch (e) { console.log(e) alert('Failed to upload file') } } } } </script> ```
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值