bootstrap-upload上傳圖片

html頁面javascript

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>

<link th:href="@{/bootstrap/css/bootstrap.css}" type="text/css" rel="stylesheet" />
<link th:href="@{/css/fileinput.css}" type="text/css" rel="stylesheet" />

<body>

	<!-- 
<input id="f_upload" type="file" class="file" data-allowed-file-extensions='["jpg","png"]'/> -->

<input id="file-4" type="file" name="photo" class="file" data-upload-url="/upload" multiple="multiple">
	
<script type="text/javascript" th:src="@{/js/jquery-3.2.1.min.js}"></script>
<script type="text/javascript" th:src="@{/js/bootstrap.js}"></script>
<script type="text/javascript" th:src="@{/js/locales/zh.js}"></script>

<script src="js/plugins/sortable.js" type="text/javascript"></script>
<script src="js/fileinput.js" type="text/javascript"></script>
<script src="js/locales/fr.js" type="text/javascript"></script>
<script src="js/locales/es.js" type="text/javascript"></script>
<script src="themes/explorer-fa/theme.js" type="text/javascript"></script>
<script src="themes/fa/theme.js" type="text/javascript"></script>
<script type="text/javascript">
	$(function() {
	})
</script>
</body>
</html>

後臺使用servlet3.0的part用於上傳css

@RequestMapping("/upload")
	@ResponseBody
	public String upload(HttpServletRequest request) throws IOException, ServletException {
		
		String dir = System.getProperty("user.dir");
		
		Part p = request.getPart("photo");
		System.out.println(p.getSubmittedFileName());
		p.write(dir+File.separator+p.getSubmittedFileName());
		
		
		return "index";
	}
 @GetMapping("/refund/download")
    public void download(OrderRefund orderRefund, HttpServletResponse response) throws IOException{
        if(orderRefund.getFileNames().size()==1){//單文件下載
            downloadOneFile(orderRefund, response);
        }else {//多文件下載
            downloadMultiFile(orderRefund,response);
        }
    }
 @ResponseBody
    @RequestMapping(value = "/refund/upload",method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Msg upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
            String refundOrderId=request.getParameter("id");
            File fileUploadPath=new File(SystemProperties.FILE_UPLOAD_PATH +refundOrderId);
            if (!fileUploadPath.exists()){
                fileUploadPath.mkdirs();
            }
        if (ServletFileUpload.isMultipartContent(request)) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                List<MultipartFile> fileList = multipartRequest.getFiles("reportFile");
                for (MultipartFile item : fileList) {
                    String fileName = item.getOriginalFilename();       //當前上傳文件全名稱
                    File savedFile = new File(fileUploadPath.getAbsolutePath(), fileName);
                    item.transferTo(savedFile);
                }
            }
            return Msg.success();
    }
    /**
     *
     * @description  下載單個文件
     * @author liyhu
     * @date 2018/7/15 11:14
     * @return void
     **/
    private void downloadOneFile(OrderRefund orderRefund, HttpServletResponse response) throws IOException{
        String fileName = orderRefund.getFileNames().get(0);
        File file = new File(new File(SystemProperties.FILE_UPLOAD_PATH +
                orderRefund.getId()).getAbsolutePath(),  fileName);

        response.setContentType("application/force-download");// 設置強制下載不打開
        response.addHeader("Content-Disposition",
                "attachment;fileName=" +URLEncoder.encode(fileName,"UTF-8"));// 設置文件名
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            logger.error("單文件下載失敗:",e);
        } finally {
            IOUtils.close(os);
            IOUtils.close(bis);
            IOUtils.close(fis);
        }
    }
    /**
     *
     * @description  打包成zip進行下載
     * @author liyhu
     * @date 2018/7/15 11:13
     * @return void
     **/
    private void downloadMultiFile(OrderRefund orderRefund, HttpServletResponse response) throws IOException{
        response.setContentType("application/x-msdownload");
        response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode("附件.zip", "utf-8"));

        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        BufferedOutputStream bos = new BufferedOutputStream(zos);

        try{
            for(String fileName:orderRefund.getFileNames()){
                File file = new File(new File(SystemProperties.FILE_UPLOAD_PATH +orderRefund.getId()).getAbsolutePath(), fileName);
                if(file.exists()){
                    BufferedInputStream bis=null;
                    try{
                        bis = new BufferedInputStream(new FileInputStream(file));
                        zos.putNextEntry(new ZipEntry(fileName));
                        int len = 0;
                        byte[] buf = new byte[10 * 1024];
                        while( (len=bis.read(buf, 0, buf.length)) != -1){
                            bos.write(buf, 0, len);
                        }
                        bos.flush();
                    }finally {
                        IOUtils.close(bis);
                    }
                }else{
                    logger.error("文件:{}不存在",file.getAbsolutePath());
                }
            }
        }catch (IOException e){
            logger.error("多文件下載失敗:",e);
        } finally{
            IOUtils.close(bos);
            IOUtils.close(zos);
        }
    }
相關文章
相關標籤/搜索