1. 程式人生 > >java檔案下載前後臺程式碼

java檔案下載前後臺程式碼

.showFileName1{

display: inline-block;

float: right;

margin-top: -38px;

margin-right: 108px;

}

.a-upload{

position: relative;

cursor: pointer;

overflow: hidden;

display: inline-block;

color: #fff;

}

.a-uploadinput{

position: absolute;

right: 0;

top: 0;

opacity: 0;

filter: alpha(opacity=0);

cursor: pointer;

}

<div class="showFileName1"

>

<a href="javascript:;" class="btn btn-success  a-upload"><input type="file" file-model="myFile" onchange="change()" >匯入Excel<iframe id="id_iframe" name="id_iframe" style="display:none;"></iframe></a>

</div>

$(".a-upload").on("change","input[type='file']",function(){

var filePath = $(this).val();

var arr= filePath.split('\\');

var fileName = arr[arr.length-1];

$(".showFileName1").html(fileName);

})

function change(){

var formData = new FormData();

var file = document.querySelector('input[type=file]').files[0];

    formData.append('logo', file);

    $.ajax({

type:'post',

url:

'../apis/analysisexcel',

data:formData,

// 告訴jQuery不要去處理髮送的資料

processData : false,

// 告訴jQuery不要去設定Content-Type請求頭

contentType : false,

dataType: "json",

success:function(data){

alert(66);

},

error:function(data){

alert(77);

}

})

}

@RequestMapping(value="/analysisexcel",produces = { "application/json" },method = RequestMethod.POST)

@ResponseBody

publicvoid analysisexcel(@RequestParam(value = "logo", required = true) MultipartFile logo,HttpServletRequest request){

try {

request.setCharacterEncoding("utf-8");

//獲取輸入流

InputStream is = logo.getInputStream();

//獲取檔案原始名稱

//String fileName = new String(logo.getOriginalFilename().getBytes(),"utf-8");

String fileName = null;

//解析器解析request的上下文

CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

//先判斷request中是否包含multipart型別的資料

if(multipartResolver.isMultipart(request)){

//再將request中的資料轉化成multipart型別的資料

MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;

Iteratoriter = multiRequest.getFileNames();

while(iter.hasNext()){

//記錄上傳過程起始的時間,用來計算上傳時間

//intpre = (int) System.currentTimeMillis();

//這裡的name為fileItem的alias屬性值相當於form表單中的name

String name = (String)iter.next();

//根據name值拿取/檔案

MultipartFile file = multiRequest.getFile(name);

if(file != null){

fileName = file.getOriginalFilename();

String path = "D:/excel/"+fileName;

File localFile = new File(path);

if(!localFile.getParentFile().exists()){

//如果目標檔案所在的目錄不存在,則建立父目錄

localFile.getParentFile().mkdirs();

}

//寫檔案到本地

try {

file.transferTo(localFile);

} catch (Exception e) {

e.printStackTrace();

}

}

}

}else{

System.out.println("不包含multipart型別的資料");

}

} catch (Exception e) {

e.printStackTrace();;

}

}