java pdf 檔案上傳
阿新 • • 發佈:2018-11-18
上傳型別
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 ><inputid="file" type="file" accept=".pdf" name="file" size="chars"></td> </tr> </table>
</form>
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; } vara = 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){ } }); };
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("成功"); }
注:tomcat預設最多上傳2M,所以如果上傳檔案大小超過2M就報錯