BootStrap fileupload实现文件上传

1、jsp使用

	<div class="form-group" style="width: 100%;height: 30%">
         <label class="col-sm-2 control-label" style="margin-left: 1.5%" for="ds_sbook">课程书籍</label>
         <div class="col-sm-4" style="width: 77%;margin-left:0.35%;height: 13%;">
	         <input type="file" name="bookfile" id="ds_sbook" data-ref="url4" class="col-sm-10 bookfile" value="" />
	         <input type="hidden" name="url4" value="">
         </div>
    </div>
    <script type="text/javascript">
	    $(".bookfile").fileinput({
	        language : 'zh',
	        uploadUrl:"/file/bookUpload",
	        uploadAsync : true, //默认异步上传
	        showUpload : true, //是否显示上传按钮,跟随文本框的那个
	        showRemove : true, //显示移除按钮,跟随文本框的那个
	        showCaption : true,//是否显示标题,就是那个文本框
	        showPreview : false, //是否显示预览,不写默认为true
	        uploadProgress : false,
	        dropZoneEnabled : false,//是否显示拖拽区域,默认不写为true,但是会占用很大区域
	        //minImageWidth: 50, //图片的最小宽度
	        //minImageHeight: 50,//图片的最小高度
	        //maxImageWidth: 1000,//图片的最大宽度
	        //maxImageHeight: 1000,//图片的最大高度
	        //maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
	        //minFileCount: 0,
	        maxFileCount : 1, //表示允许同时上传的最大文件个数
	        enctype : 'multipart/form-data',
	        validateInitialCount : true,
	        previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
	        msgFilesTooMany : "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
	        allowedFileExtensions : [ 'pdf' ]//配置允许文件上传的类型
	    });
	    //异步上传返回结果处理
	    $('.bookfile').on('fileerror', function(event, data, msg) {
	        console.log("fileerror");
	        console.log(data);
	    });
	    //异步上传返回结果处理
	    $(".bookfile").on("fileuploaded", function(event, data, previewId, index) {
	        console.log("fileuploaded");
	        var ref = $(this).attr("data-ref");
	        $("input[name='" + ref + "']").val(data.response.url);
	
	    });
	
	    //同步上传错误处理
	    $('.bookfile').on('filebatchuploaderror', function(event, data, msg) {
	        console.log("filebatchuploaderror");
	        console.log(data);
	    });
	
	    //同步上传返回结果处理
	    $(".bookfile").on("filebatchuploadsuccess",
	        function(event, data, previewId, index) {
	            console.log("filebatchuploadsuccess");
	            console.log(data);
	        });
	
	    //上传前
	    $('.bookfile').on('filepreupload', function(event, data, previewId, index) {
	        console.log("filepreupload");
	    });
	</script>

2、controller

package com.graduation.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author K
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping(value = "/download",method = RequestMethod.GET)
    private ResponseEntity<byte[]> FileDownload(HttpServletRequest request, @RequestParam(value = "filename",required = true) String filename, Model model)throws IOException {
        String path = request.getServletContext().getRealPath("");

        String downloadFilePath=path + "\\static\\datafile";//从我们的上传文件夹中去取
        filename = filename+".zip";
        File file = new File(downloadFilePath+File.separator+filename);//新建一个文件

        HttpHeaders headers = new HttpHeaders();//http头信息

        String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");//设置编码

        headers.setContentDispositionFormData("attachment", downloadFileName);

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }
    @RequestMapping(value = "/templateDownload",method = RequestMethod.GET)
    private ResponseEntity<byte[]> TemplateDownload(HttpServletRequest request, @RequestParam(value = "filename",required = true) String filename, Model model)throws IOException {
        String path = request.getServletContext().getRealPath("");

        String downloadFilePath=path + "\\static\\template";//从我们的上传文件夹中去取
        filename = filename+".xlsx";
        File file = new File(downloadFilePath+File.separator+filename);//新建一个文件

        HttpHeaders headers = new HttpHeaders();//http头信息

        String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");//设置编码

        headers.setContentDispositionFormData("attachment", downloadFileName);

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }
    @ResponseBody
    @RequestMapping("/upload")
    public Map<String, Object> uploadFile(MultipartFile coverImg,HttpServletRequest request) throws IllegalStateException, IOException {
        // 原始名称
        String oldFileName;
        oldFileName = coverImg.getOriginalFilename();
        // 上传图片
        if (coverImg != null && oldFileName != null && oldFileName.length() > 0) {
            // 新的图片名称
            String newFileName = oldFileName;
            //存放地址
            String saveFilePath = request.getServletContext().getRealPath("")+"\\static\\imgs\\courseImg\\"+newFileName;
            // 新图片
            File newFile = new File(saveFilePath);
            // 将内存中的数据写入磁盘
            coverImg.transferTo(newFile);
            // 将新图片名称返回到前端
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", "成功啦");
            map.put("url", newFileName);
            return map;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("error", "图片不合法");
            return map;
        }
    }

    @ResponseBody
    @RequestMapping("/courseUpload")
    public Map<String, Object> uploadCourseFile(MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException {
        // 原始名称
        String oldFileName;
        oldFileName = file.getOriginalFilename();
        String suffix = oldFileName.substring(oldFileName.indexOf(".")+1);
        // 上传图片
        if (file != null && oldFileName != null && oldFileName.length() > 0) {
            // 新的图片名称
            String newFileName = oldFileName;
            String saveFilePath;
            //存放地址
            if(suffix.equals("docx") || suffix.equals("doc")){
                saveFilePath = request.getServletContext().getRealPath("")+"\\static\\exercises\\"+newFileName;

            }else if(suffix.equals("zip")||suffix.equals("rar")){
                saveFilePath = request.getServletContext().getRealPath("")+"\\static\\datafile\\"+newFileName;
            }else{
                saveFilePath = request.getServletContext().getRealPath("")+"\\static\\videos\\"+newFileName;
            }
            // 新图片
            File newFile = new File(saveFilePath);
            // 将内存中的数据写入磁盘
            file.transferTo(newFile);
            // 将新图片名称返回到前端
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", "成功啦");
            map.put("url", newFileName);
            return map;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("error", "图片不合法");
            return map;
        }
    }

    @ResponseBody
    @RequestMapping("/planfile")
    public Map<String, Object> uploadPlane(MultipartFile planfile,HttpServletRequest request) throws IllegalStateException, IOException {
        // 原始名称
        String oldFileName;
        oldFileName = planfile.getOriginalFilename();

        // 上传图片
        if (planfile != null && oldFileName != null && oldFileName.length() > 0) {
            // 新的图片名称
            String newFileName = oldFileName;
            //存放地址
            String saveFilePath = request.getServletContext().getRealPath("")+"\\static\\teachPlans\\"+newFileName;
            // 新图片
            File newFile = new File(saveFilePath);
            // 将内存中的数据写入磁盘
            planfile.transferTo(newFile);
            // 将新图片名称返回到前端
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", "成功啦");
            map.put("url", newFileName);
            return map;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("error", "图片不合法");
            return map;
        }
    }

    @ResponseBody
    @RequestMapping("/bookUpload")
    public Map<String, Object> uploadBook(MultipartFile bookfile,HttpServletRequest request) throws IllegalStateException, IOException {
        // 原始名称
        String oldFileName;
        System.out.println("原始名称:"+bookfile.getOriginalFilename());
        oldFileName = bookfile.getOriginalFilename();
        // 上传图片
        if (bookfile != null && oldFileName != null && oldFileName.length() > 0) {
            // 新的图片名称
            String newFileName = oldFileName;
            //存放地址
            String saveFilePath = request.getServletContext().getRealPath("")+"\\static\\chapterPdf\\"+newFileName;
            // 新图片
            File newFile = new File(saveFilePath);
            // 将内存中的数据写入磁盘
            bookfile.transferTo(newFile);
            // 将新图片名称返回到前端
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", "成功啦");
            map.put("url", newFileName);
            return map;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("error", "图片不合法");
            return map;
        }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值