springMVC文件上传下载

jsp文件内容

完整jsp代码

文件上传

 <form id="addproductform" enctype="multipart/form-data" >

<td align="right">上传附件: </td>
<td>
<input type="file" onchange="upload()" name="download" ></input>
</td>
</tr>
<tr>
<td align="right">文件路径: </td>
<td>
<input name="filePath" id="filePath" type="text" readonly="readonly"></input>
</td>
<td align="right">上传附件: </td>
<td>
<input type="text" name="myfiles" id="myfiles" readonly="readonly"></input>
</td>
</tr>

</form>

 

function upload(){

//var myfiles =$('#myfiles').val();
var fomdata=new FormData($('#addproductform')[0])
//alert('进来看看fomdata=='+fomdata)

$.ajax({
url:'<%=basePath%>file/fileUpload.do',//地址
data:fomdata,
type:'post',//类型
cache:false,
processData:false,
contentType:false,
//请求成功
success:function(data){
//alert(data.fileName);
var filePath=data.filePath;
$("#filePath").val(filePath);
$("#myfiles").val(data.fileName);

},
//失败/超时
error:function(XMLHttpRequest,textStatus,errorThrown){
if(textStatus==='timeout'){
alert('請求超時');
setTimeout(function(){
alert('重新请求');
},2000);
}
//alert(errorThrown);
}
})

文件下载

<form id="updateproductform">

<tr>

<td align="right">上传附件: </td>
<td>
<input type="text" name="myfiles" id="myfilesdown" readonly="readonly"></input>
</td>
</tr>
<tr>
<td align="right">文件路径: </td>
<td>
<input name="filePath" id="filePathdown" type="text" readonly="readonly"></input>
</td>
<td align="right">下载: </td>
<td>
<input value="下载" type="button" onclick="download()"></input>
</td>
</tr>

function download(){
var fileName=$('#myfilesdown').val();
var filePathdown=$('#filePathdown').val();
if(null!=fileName&&""!=fileName){
window.location.href="<%=basePath%>file/download.do?fileName="+fileName;
}
}

后台代码==

package controller.files;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.web.bind.annotation.PathVariable;
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;

@Controller
@RequestMapping("/file")
public class FileUploadController {
//文件上传
@RequestMapping("/fileUpload.do")
@ResponseBody
public Map fileUpload(@RequestParam("download") MultipartFile file, HttpServletRequest request) {
System.out.println("file====================="+file);
Map<String,Object>map=new HashMap<String,Object>();
try {
if (!file.isEmpty()) {
String storePath = "D://images";
Random r = new Random();
String fileName = file.getOriginalFilename();
String[] split = fileName.split(".jpg");
fileName = split[0] + r.nextInt(1000);
fileName = fileName + ".jpg";
File filePath = new File(storePath, fileName);
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();// 如果目录不存在,则创建目录
}
file.transferTo(new File(storePath + File.separator + fileName));// 把文件写入目标文件地址
System.out.println("filePath+fileName="+filePath+fileName);
map.put("msg", "上传成功");
map.put("success", "success");
map.put("filePath", storePath);
map.put("fileName", fileName);
}


} catch (Exception e) {
e.printStackTrace();
map.put("msg", "上传失败");
}
return map;

}


//文件下载
@RequestMapping("/download.do")
public void download(@RequestParam("fileName")String filename,HttpServletRequest req,HttpServletResponse resp) throws IOException{
System.out.println("filename=="+filename);
//设置响应流文件进行下载
resp.setHeader("Content-Disposition","attachment;filename="+filename);
ServletOutputStream sos = resp.getOutputStream();
File file = new File("D://images", filename);//这个路径为磁盘开始

byte[] bytes = FileUtils.readFileToByteArray(file);
sos.write(bytes);
sos.flush();
sos.close();
}


}

完整jsp页面代码

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<meta charset="utf-8">
<link href="<%=basePath%>css/themes/default/easyui.css" rel="stylesheet" type="text/css"/>
<%-- <link href="<%=basePath%>css/themes/icon.css" rel="stylesheet" type="text/css"/> --%>
<link href="<%=basePath%>css/themes/color.css" rel="stylesheet" type="text/css"/>
<%-- <link href="<%=basePath%>css/themes/mobile.css" rel="stylesheet" type="text/css"/> --%>


<script type="text/javascript" src="<%=basePath%>js/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>js/easyloader.js"></script>
<script type="text/javascript" src="<%=basePath%>js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="<%=basePath%>js/jquery.easyui.mobile.js"></script>
<script type="text/javascript" src="<%=basePath%>js/plugins/jquery.parser.js"></script>
<script type="text/javascript" src="<%=basePath%>js/plugins/jquery.pagination.js"></script>
<script type="text/javascript" src="<%=basePath%>js/plugins/jquery.form.js"></script>
<style type="text/css">
#producttable{
width: 90%;
border-collapse:separate; border-spacing:0px 20px;
}
#producttable input{
height:32px;
}
</style>

 

</head>
<body>

<div style="height: 800px;margin-top: 35px;">
<table id="listtable">

</table>
</div>
<!-- 添加产品 -->
<div id="addproduct">
<form id="addproductform" enctype="multipart/form-data" >
<table id="producttable">
<tr>
<td align="right">生产人: </td>
<td>
<input id="creat_pepole" name="creat_pepole"></input>
</td>
<td align="right">产品名称:</td>
<td>
<input id="product_name" name="product_name"></input>
</td>
</tr>
<tr>
<td align="right">生产时间: </td>
<td>
<input id="creat_time" name="creat_time" class="easyui-datebox" required="required"></input>
</td>
<td align="right">产品数量:</td>
<td>
<input id="product_count" name="product_count"></input>
</td>
</tr>
<tr>
<td align="right">生产编号: </td>
<td>
<input id="creat_num" name="creat_num"></input>
</td>
<td align="right">生产地址:</td>
<td>
<input id="product_addres" name="product_addres"></input>
</td>
</tr>
<tr>
<td align="right">保质期: </td>
<td>
<select id="save_time" name="save_time" style="width: 170px;height: 32px;">
<option value="5" selected="selected">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
</td>
<td align="right">上传附件: </td>
<td>
<input type="file" onchange="upload()" name="download" ></input>
</td>
</tr>
<tr>
<td align="right">文件路径: </td>
<td>
<input name="filePath" id="filePath" type="text" readonly="readonly"></input>
</td>
<td align="right">上传附件: </td>
<td>
<input type="text" name="myfiles" id="myfiles" readonly="readonly"></input>
</td>
</tr>
</table>
</form>
</div>
<!-- 修改产品 -->
<div id="updateproduct">
<form id="updateproductform" enctype="multipart/form-data">
<table id="producttable">
<tr>
<td align="right">生产人: </td>
<td>
<input id="creat_pepole" name="creat_pepole"></input>
</td>
<td align="right">单位类别:</td>
<td>
<input id="product_name" name="product_name"></input>
</td>
</tr>
<tr>
<td align="right">生产时间: </td>
<td>
<input id="creat_time" name="creat_time" class="easyui-datebox" required="required"></input>
</td>
<td align="right">产品数量:</td>
<td>
<input id="product_count" name="product_count"></input>
</td>
</tr>
<tr>
<td align="right">生产编号: </td>
<td>
<input id="creat_num" name="creat_num"></input>
</td>
<td align="right">生产地址:</td>
<td>
<input id="product_addres" name="product_addres"></input>
</td>
</tr>
<tr>
<td align="right">保质期: </td>
<td>
<select id="save_time" name="save_time" style="width: 170px;height: 32px;">
<option value="5" selected="selected">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
</td>
<td align="right">附件名称: </td>
<td>
<input type="text" name="myfiles" id="myfilesdown" readonly="readonly"></input>
<input value="下载" type="button" onclick="filedownload()" id="updatedownload"></input>
<input type="file" onchange="updateupload()" name="download" id="uploadfile"></input>
</td>
</tr>
<tr>
<td align="right">文件路径: </td>
<td>
<input name="filePath" id="filePathdown" type="text" readonly="readonly"></input>
</td>

</tr>
</table>
</form>
</div>
<script type="text/javascript">
function filedownload(){

var fileName=$('#myfilesdown').val();
var filePathdown=$('#filePathdown').val();
if(null!=fileName&&""!=fileName){
window.location.href="<%=basePath%>file/download.do?fileName="+fileName;
}
}
//修改文件上传
function updateupload(){
//var myfiles =$('#myfiles').val();

var fomdata=new FormData($('#updateproductform')[0])
//alert('进来看看fomdata=='+fomdata)

$.ajax({
url:'<%=basePath%>file/fileUpload.do',//地址
data:fomdata,
type:'post',//类型
cache:false,
processData:false,
contentType:false,
//请求成功
success:function(data){
//alert(data.fileName);
var filePath=data.filePath;
$("#filePathdown").val(filePath);
$("#myfilesdown").val(data.fileName);

},
//失败/超时
error:function(XMLHttpRequest,textStatus,errorThrown){
if(textStatus==='timeout'){
alert('請求超時');
setTimeout(function(){
alert('重新请求');
},2000);
}
//alert(errorThrown);
}
})
}


//文件上传添加
function upload(){

//var myfiles =$('#myfiles').val();

var fomdata=new FormData($('#addproductform')[0])
//alert('进来看看fomdata=='+fomdata)

$.ajax({
url:'<%=basePath%>file/fileUpload.do',//地址
data:fomdata,
type:'post',//类型
cache:false,
processData:false,
contentType:false,
//请求成功
success:function(data){
//alert(data.fileName);
var filePath=data.filePath;
$("#filePath").val(filePath);
$("#myfiles").val(data.fileName);

},
//失败/超时
error:function(XMLHttpRequest,textStatus,errorThrown){
if(textStatus==='timeout'){
alert('請求超時');
setTimeout(function(){
alert('重新请求');
},2000);
}
//alert(errorThrown);
}
})
<%-- window.location.href="<%=basePath%>files/toUpload.do"; --%>
}

//设置日期格式
$.fn.datebox.defaults.formatter = function(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return y+'-'+m+'-'+d;
}

//添加用户
$('#addproduct').dialog({
title:'添加用户',
width:'50%',
height:'600px',
iconCls:'icon-add',
closed:true,
closable: true,
draggable: false,
modal: true,
buttons:[ {
text : '保存',
iconCls : 'icon-ok',
handler : function() {
$('#addproductform').form('submit',{
onSubmit:function(){
return $(this).form('enableValidation').form('validate');
},
url:'<%=basePath%>product/addProduct.do',
success : function(data) {
data = eval("(" + data + ")");//JSON字符串转对象
$.messager.show({
title:'提示',
msg: data.msg,
showType:'show'
});
$('#addproduct').dialog('close');
$('#listtable').datagrid('reload');
},
error: function(){
$.messager.show({
title:'提示',
msg: '添加失败',
showType:'show'
});
}
});
}
}, {
text : '取消',
iconCls : 'icon-cancel',
handler : function() {
$('#addproduct').dialog('close');
}
} ]
});
//修改产品

$('#updateproduct').dialog({
title:'添加用户',
width:'50%',
height:'600px',
iconCls:'icon-add',
closed:true,
closable: true,
draggable: false,
modal: true,
buttons:[ {
text : '保存',
iconCls : 'icon-ok',
handler : function() {
$('#updateproductform').form('submit',{
onSubmit:function(){
return $(this).form('enableValidation').form('validate');
},
url:'<%=basePath%>product/supdateProduct.do',
success : function(data) {
alert(data)
data = eval("(" + data + ")");//JSON字符串转对象
$.messager.show({
title:'提示',
msg: data.msg,
showType:'show'
});
$('#updateproduct').dialog('close');
$('#listtable').datagrid('reload');
},
error: function(){
$.messager.show({
title:'提示',
msg: data.msg,
showType:'show'
});
}
});
}
}, {
text : '取消',
iconCls : 'icon-cancel',
handler : function() {
$('#updateproduct').dialog('close');
}
} ]
});
$('#addproduct').dialog('close');
$('#updateproduct').dialog('close');
$('#listtable').datagrid({
width: 'auto',
height:'auto',
striped: true,
fit: true,
pagination: true,
scrollbarSize: 0,
singleSelect: true,
url: '<%=basePath%>product/findProductList.do',
loadMsg: '数据加载中请稍后……',
columns: [[{
field: 'product_no',
title: '产品编号',
align: 'center',
resizable: false,
width: '10%'
},{
field: 'product_name',
title: '产品名',
align: 'center',
resizable: false,
width: '15%'
}, {
field: 'creat_time',
title: '生产日期',
align: 'center',
resizable: false,
width: '15%'
}, {
field: 'product_count',
title: '产品数量',
align: 'center',
resizable: false,
width: '15%'
}, {
field: 'creat_num',
title: '生产编号',
align: 'center',
resizable: false,
width: '15%'
}, {
field: 'product_addres',
title: '生产地址',
align: 'center',
resizable: false,
width: '15%'
}, {
field: 'creat_pepole',
title: '生产人',
align: 'center',
resizable: false,
width: '15%'
}, {
field: 'save_time',
title: '保质期',
align: 'center',
resizable: false,
width: '15%'
}, {
field: 'myfiles',
title: '文件名称',
align: 'center',
resizable: false,
width: '15%'
}, {
field: 'filePath',
title: '文件路径',
align: 'center',
resizable: false,
width: '15%'
}
]],
method: 'post',
toolbar: [{
text:'添加',
iconCls: 'icon-edit',
handler: function(){
$('#addproductform').form('clear');
$('#addproduct').dialog('open').dialog('setTitle', '添加产品');
$("#save_time").val(Array('5'))
}
},'-',{
text:'修改',
iconCls: 'icon-help',
handler: function(){
var row=$('#listtable').datagrid('getSelected');
if(row){

$('#updateproductform').form('load',row);
var myfiles=row.myfiles;
//alert(myfiles)
if(null!=myfiles&&""!=myfiles){
$("#uploadfile").hide();//隐藏
$("#updatedownload").show();//显示
}else{
$("#updatedownload").hide();//隐藏
$("#uploadfile").show();//显示
}
$('#updateproduct').dialog('open').dialog('setTitle', '添加产品');

}else{
$.messager.show({
title:'提示',
msg: '至少选择一条',
showType:'show'
});
}

}
},'-',{
text:'删除',
iconCls: 'icon-help',
handler: function(){
var row=$('#listtable').datagrid('getSelected');
if(row){
$.messager.confirm('删除数据', '您确定删除此用户吗?', function(r){
if (r){
$.post('<%=basePath%>product/deleteProduct.do?product_no=' + row.product_no,
function (result) {
$.messager.show({
title:'提示',
msg: result.msg,
showType:'show'
});
$('#listtable').datagrid('reload');

},'json');
}
});

 

}else{
$.messager.show({
title:'提示',
msg: '至少选择一条',
showType:'show'
});
}

}
}]
});

var p = $('#listtable').datagrid('getPager');
$(p).pagination({
pageSize : 10,//每页显示的记录条数,默认为10
pageList : [10, 20, 30],//可以设置每页记录条数的列表
beforePageText : '第',//页数文本框前显示的汉字
afterPageText : '页 共 {pages} 页',
displayMsg : '当前显示 {from} - {to} 条记录 共 {total} 条记录',
});
</script>
</body>
</html>

posted @ 2019-12-08 00:07  红尘沙漏  阅读(314)  评论(0编辑  收藏  举报