java web檔案上傳與下載
阿新 • • 發佈:2018-11-05
jsp程式碼(檔案上傳)
-
<form id="upLoad" method="post">
-
<input type="file" id="yaFile" name="file">
<br/>
-
<input
id="fileSubmit" type="button" value="提交">
-
</form>
js程式碼:這裡我選擇的是非同步提交
-
$("#fileSubmit").click(function(){
-
var formData = new FormData();
-
formData.append("file", document.getElementById("upLoad").files[0]);
-
$.ajax({
-
cache: true,
-
type: "POST",
-
url:'路徑',
-
data:formData,
-
processData: false,
//禁止jquery對DAta資料的處理,預設會處理
-
contentType: false,
//禁止設定請求型別
-
async: false,
-
error: function(request) {
-
alert("上傳失敗");
-
},
-
success: function(data) {
-
if(data==0){
alert("上傳成功");
} } });});
java程式碼:檔案上傳
-
/**
-
* 檔案上傳功能
-
* @param file
-
* @return
-
* @throws IOException
-
*/
-
@RequestMapping(
"/upload")
-
@ResponseBody
-
public String upload(MultipartFile file,String faUrl,HttpServletRequest request) throws IOException{
-
String path = request.getSession().getServletContext().getRealPath(
"upload");
//檔案上傳路徑
-
String fileName = file.getOriginalFilename();
-
File dir =
new File(path ,fileName);
-
if(!dir.exists()){
-
dir.mkdirs();
-
}
-
//MultipartFile自帶的解析方法
-
file.transferTo(dir);
-
return
"0";
-
}
js程式碼:檔案下載
- function onClick() {
- var url ="路徑"
- document.location.href=url;
- }
java程式碼:檔案下載
-
/**
-
* 檔案下載功能
-
* @param request
-
* @param response
-
* @throws Exception
-
*/
-
@RequestMapping(
"/fileDown")
-
@ResponseBody
-
public void fileDown(HttpServletRequest request,HttpServletResponse response){
-
//通過檔名找出檔案的所在目錄
-
String path = request.getSession().getServletContext().getRealPath(
"upload");
-
ServletOutputStream out;
-
//得到要下載的檔案
-
File file =
new File(path);
-
try {
-
//設定響應頭,控制瀏覽器下載該檔案
-
response.setContentType(
"multipart/form-data");
-
//獲得瀏覽器資訊,並處理檔名
-
String headerType=request.getHeader(
"User-Agent").toUpperCase();
-
String fileName =
null;
-
if (headerType.indexOf(
"EDGE") >
0||headerType.indexOf(
"MSIE")>
0||headerType.indexOf(
"GECKO")>
0) {
-
fileName=URLEncoder.encode(file.getName(),
"UTF-8");
-
}
else{
-
fileName=
new String(file.getName().replaceAll(
" ",
"").getBytes(
"utf-8"),
"iso8859-1");
-
}
-
response.addHeader(
"Content-Disposition",
"attachment;filename="+fileName);
-
response.addHeader(
"Content-Length",
"" + file.length());
-
FileInputStream inputStream =
new FileInputStream(file);
-
-
out = response.getOutputStream();
-
-
int b =
0;
-
byte[] buffer =
new
byte[
1024];
-
while (b != -
1) {
-
b = inputStream.read(buffer);
-
//寫到輸出流(out)中
-
if(b!=-
1)
-
out.write(buffer,
0, b);
-
}
-
inputStream.close();
-
out.close();
//關閉輸出流
-
out.flush();
-
}
catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
以上為檔案上傳、檔案下載的全部程式碼。