1.前端需要限制上传类型 accept =".pdf" 限制只有pdf的可以上传
<form action="clientCreditQueryOrder_importFile.do" id="form2" enctype="multipart/form-data" method="post" >
<table width="100%">
<input id="ccqoid" hidden="hidden" />
<tr>
<td >附件:</td> <td ><input id="file" type="file" accept=".pdf" name="file" size="chars"></td>
</tr>
</table>
</form>
2,js编写
function myUpLoadFile(i){
var form = myUp.find('form:first');
myUp.dialog({
title:'上传附件',
width:'340',
height:'160',
buttons:[{
text:'确定',
handler:function(){
console.log(i+" ------");
$("#ccqoid").val(i);
var file = document.getElementById('file').files[0];
if(file == null){
$.messager.alert('提示',"请选择上传文件");
return false;
}
var a = 2;
var b = file.size;
var c = b/(1024 * 1024);
if(c>a){
$.messager.alert('提示',"上传失败,建议文件大小为2M以内");
return false;
}
submitForm(i);
}},
{
text:'取消',
handler:function(){
myUp.dialog('close');
}
}]
});
myUp.dialog('open');
}
function submitForm(i){
var formDate=new FormData($("#form2")[0]);
$.ajax({
url:'upload_importFile.do?ccqoid='+i,
type:'POST',
data:formDate,
async:false,
cache:false,
contentType:false,
processData:false,
success:function(data){
if(data.success){
$.messager.alert('提示','导入成功!');
myUp.dialog('close');
dg.datagrid('refreshReload');
}
},
error:function(returndata){
}
});
};
2。后端java代码编写
private String fileFileName;
private File file;
private String ccqoid;
private String fileContentType;
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getCcqoid() {
return ccqoid;
}
public void setCcqoid(String ccqoid) {
this.ccqoid = ccqoid;
}
/**
* 上传pdf文件 * @throws IOException
*/
public JObject importFile() throws IOException {
String savePath = Constants.PDF_SAVEPATH;
String relPath = "";
File f1 = new File(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
if (fileFileName == null || ("".equals(fileFileName))) {
throw new RuntimeException("请选择文件!");
}
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String format = df.format(new Date());
InputStream inputStream = new FileInputStream(file);
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = null;
try {
relPath = savePath + "" + format + "-" + fileFileName;
fileOutputStream = new FileOutputStream(relPath);
while ((len = inputStream.read(data)) != -1) {
fileOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new JResult("成功");
}