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;
}
}
}