這篇文章主要講解了SpringMvc3+extjs4實(shí)現(xiàn)上傳與下載功能的代碼解析,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。

成都創(chuàng)新互聯(lián)專注于蓮花企業(yè)網(wǎng)站建設(shè),自適應(yīng)網(wǎng)站建設(shè),商城網(wǎng)站建設(shè)。蓮花網(wǎng)站建設(shè)公司,為蓮花等地區(qū)提供建站服務(wù)。全流程定制開發(fā),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
本文實(shí)例為大家分享了SpringMvc3+extjs4實(shí)現(xiàn)上傳與下載的具體代碼,供大家參考,具體內(nèi)容如下
最近生活過(guò)的很充實(shí),人一直在不停的忙碌著學(xué)習(xí)新東西。這是我最近遇到的問(wèn)題,我找度娘n了很久,終于找到了解決方案!
前臺(tái)代碼:
<script>
Ext.onReady(function() {
Ext.create('Ext.form.Panel', {
title : '文件上傳',
width : 400,
bodyPadding : 10,
frame : true,
renderTo : document.body,
items : [ {
xtype : 'filefield',
name : '文件',
fieldLabel : 'File',
labelWidth : 50,
msgTarget : 'side',
allowBlank : false,
anchor : '100%',
buttonText : '請(qǐng)選擇文件...'
} ],
buttons : [ {
text : '上傳',
handler : function() {
var form = this.up('form').getForm();
if (form.isValid()) {
form.submit({
url : '根路徑/fileUploadDown/fileUpload',
waitMsg : '正在上傳文件中...',
success : function(fp, o) {
Ext.Msg.alert('上傳文件成功!');
}
});
}
}
} ]
});
});
</script>后臺(tái)代碼:
/**
*記錄返回結(jié)果*/
class ExtJSFormResult {
private boolean success;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
}
public String toString() {
return "{success:" + this.success + "}";
}
}
class FileUploadBean {
private CommonsMultipartFile file;
public CommonsMultipartFile getFile() {
return file;
}
public void setFile(CommonsMultipartFile file) {
this.file = file;
}
}
/**
* 文件的上傳與下載
* @author Administrator
*
*/
@Controller
@RequestMapping(value = "/fileUploadDown")
public class FileUploadAndDownController {
private static int countter=1; //定義一個(gè)計(jì)數(shù)器,用于上傳文件的重命名
@Autowired
private ProAnnexDao<ProAnnex> proAnnextDao;
public void setProAnnextDao(ProAnnexDao<ProAnnex> proAnnextDao) {
this.proAnnextDao = proAnnextDao;
}
@RequestMapping(value="fileUpload",method = RequestMethod.POST)
public @ResponseBody String create(RedirectAttributes redirectAttributes,FileUploadBean uploadItem,
BindingResult result,HttpSession session){
//獲取根路徑
String uploadFolderPath = session.getServletContext().getRealPath("/");
ExtJSFormResult extjsFormResult = new ExtJSFormResult();
try {
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
System.err.println("Error: " + error.getCode() + " - "
+ error.getDefaultMessage());
}
// 設(shè)置ExtJS返回 - error
extjsFormResult.setSuccess(false);
return extjsFormResult.toString();
}
MultipartFile file = uploadItem.getFile();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if(file.getSize()>0){
System.out.println("File Size:::" + file.getSize());
if(file.getSize()>5242880){
System.out.println("File Size:::" + file.getSize());
extjsFormResult.setSuccess(false);
return "error";
}
inputStream = file.getInputStream();
File newFile = new File(uploadFolderPath + "fileUpload/");
//如果文件路徑不存在就新建一個(gè)
if(!newFile.exists()){
newFile.mkdirs();
}
//獲取文件名
String name=file.getOriginalFilename();
//從數(shù)據(jù)庫(kù)中查詢存在此類文件名否
Long count=proAnnextDao.isRepeatName(name);
//如果存在一樣的文件名,就進(jìn)行從命名
if (count>0) {
name=name.substring(0, name.lastIndexOf("."))+"("+(countter++)+")"+name.substring(name.lastIndexOf("."));
}
fileName = uploadFolderPath + "fileUpload/" + name;
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
// 設(shè)置ExtJS返回 - sucsess
extjsFormResult.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
// 設(shè)置ExtJS返回 - error
extjsFormResult.setSuccess(false);
}
return extjsFormResult.toString();
}
}springMvc.xml(此文件名可能跟項(xiàng)目的實(shí)際情況有區(qū)別)中的配置:
<!-- 上傳文件,限制大小的配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--resolveLazily屬性啟用是為了推遲文件解析,以便在Upload中捕獲文件大小異常--> <property name="resolveLazily" value="true"/> <property name="maxUploadSize" value="5242880" /> </bean> <!-- 將無(wú)法mapping到Controller的path交給default servlet handler處理 --> <mvc:default-servlet-handler/><!-- 使用默認(rèn)的servlet來(lái)響應(yīng)靜態(tài)文件 --> <!-- 文件的上傳與下載 --> <mvc:view-controller path="/" view-name="redirect:/fileUploadDown"/>
以上的就是上傳文件了。
那下載呢?
下載比較簡(jiǎn)單,代碼如下:
@RequestMapping("/downloadFile")
public void download(@Valid @ModelAttribute("downLoadName") String downLoadName,
HttpServletResponse response,HttpSession session,BindingResult result,HttpServletRequest request) throws IOException {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
//獲取文件的路徑
String url=session.getServletContext().getRealPath("/")+"/fileUpload/"+downLoadName;
System.out.println(url);
File file=new File(url);
InputStream input = FileUtils.openInputStream(file);
byte[] data = IOUtils.toByteArray(input);
//System.out.println("文件名:"+downLoadName);
response.reset();
//設(shè)置響應(yīng)的報(bào)頭信息(中文問(wèn)題解決辦法)
response.setHeader("content-disposition","attachment;fileName="+URLEncoder.encode(downLoadName, "UTF-8"));
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
IOUtils.closeQuietly(input);
}在界面上只要有一個(gè)連接地址:如:window.location.href="根路徑/fileUploadDown/downfile/downLoadName="+name;這樣就可以下載了.... 超連接的寫法基本一樣,這里就不多說(shuō)了.
看完上述內(nèi)容,是不是對(duì)SpringMvc3+extjs4實(shí)現(xiàn)上傳與下載功能的代碼解析有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享文章:SpringMvc3+extjs4實(shí)現(xiàn)上傳與下載功能的代碼解析
新聞來(lái)源:http://www.chinadenli.net/article24/pesdce.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、云服務(wù)器、網(wǎng)站設(shè)計(jì)、微信小程序、網(wǎng)站策劃、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)