AjaxFileUpload(1)Simple File Upload Sample

本文将介绍如何利用Ajax技术实现简单的文件上传功能,包括Maven配置、额外的Spring配置、JavaScript和HTML页面的整合,以及上传过程中的安全考虑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AjaxFileUpload(1)Simple File Upload Sample

1. Maven Configuration
The jar dependecies in pom.xml are as follow:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>

2. Addtional Spring Configuration
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600"/>
<property name="maxInMemorySize" value="4096"/>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>

3. My JavaScript and HTML page
<html>
<head>
<title>AjaxFileUpload Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="./resources/component/ajaxfileupload/2.1/ajaxfileupload.js"></script>
<script type="text/javascript">

$(document).ready(function(){
$("#filemaps").change(function(){
var file_upl = document.getElementById('filemaps');
var realpath = getPath(file_upl);
$("#fileurl").val(realpath);
});
});

function userBrowser(){
var browserName=navigator.userAgent.toLowerCase();
if(/msie/i.test(browserName) && !/opera/.test(browserName)){
return "IE";
}else if(/firefox/i.test(browserName)){
return "Firefox";
}else if(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)){
return "Chrome";
}else if(/opera/i.test(browserName)){
return "Opera";
}else if(/webkit/i.test(browserName) &&!(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName))){
return "Safari";
}else{
return "unKnow";
}
}

function getPathIE(obj){
obj.select();
return document.selection.createRange().text;
}

function getPathFFSecurity(obj){
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}catch (e) {
alert('Unable to access local files due to browser security settings. To overcome this, follow these steps: (1) Enter "about:config" in the URL field; (2) Right click and select New->Boolean; (3) Enter "signed.applets.codebase_principal_support" (without the quotes) as a new preference name; (4) Click OK and try loading the file again.');
if(obj.files){
return obj.files.item(0).name;
}
return;
}
return obj.value;
}

function extractFilename(path) {
if (path.substr(0, 12) == "C:\\fakepath\\")
return path.substr(12); // modern browser
var x;
x = path.lastIndexOf('/');
if (x >= 0) // Unix-based path
return path.substr(x+1);
x = path.lastIndexOf('\\');
if (x >= 0) // Windows-based path
return path.substr(x+1);
return path; // just the filename
}

function getPath(obj){
if(obj){
//if (window.navigator.userAgent.indexOf("MSIE")>=1){
if(userBrowser() == 'IE'){
return getPathIE(obj);
//}else if(window.navigator.userAgent.indexOf("Firefox")>=1){
}else if(userBrowser() == 'Firefox'){
return getPathFFSecurity(obj);
}else if(userBrowser() == 'Chrome'){
return extractFilename(obj.value);
}
return obj.value;
}
}

function ajaxFileUpload(){
$.ajaxFileUpload(
{
url:'fileupload.do',
secureuri:false,
fileElementId:'filemaps',
dataType: 'json',
success: function (data, status)
{
console.info(data);
$('#result').html('Success to Add');
},
error: function (data, status, e)
{
$('#result').html('Fail to Add');
}
}
);
}
</script>

</head>
<body>

<h2>AjaxFileUpload Demo</h2>

<form method="post" action="fileupload.do" enctype="multipart/form-data">
<input id="fileurl" type="text" class="langtext" readonly="readonly"/>
<input type="file" id="filemaps" name="filemaps" value="upload"/>
<input type="button" value="Submit" onclick="ajaxFileUpload()"/>
</form>

<div id="result"></div>

</body>
</html>

Because of the security reason, a lot of browser does not support to get the full local path of the file.

4. Java File to handler the binary file
package com.sillycat.easytalker.controller;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class FileController {

private static final Logger logger = Logger.getLogger(FileController.class);

@RequestMapping("/fileupload.do")
public void uploadFile(MultipartHttpServletRequest request,
HttpServletResponse response) throws IOException {
MultipartFile multipartFile = request.getFile("filemaps");
if (null != multipartFile
&& null != multipartFile.getOriginalFilename()) {
logger.info("orginal file name = "
+ multipartFile.getOriginalFilename());
// OutputStream os = null;
// InputStream is = null;
// try {
// is = multipartFile.getInputStream();
// File file = new File("D:/"
// + multipartFile.getOriginalFilename());
// os = new FileOutputStream(file);
//
// byte[] b = new byte[1024];
// int len = 0;
// while ((len = is.read(b)) != -1) {
// os.write(b, 0, len);
// }
// } catch (Exception e) {
// logger.error("Error Message:" + e);
// } finally {
// os.close();
// is.close();
// }
}
}

}
references:
http://www.phpletter.com/Our-Projects/AjaxFileUpload/
http://springking.iteye.com/blog/198452
http://demos.telerik.com/aspnet-ajax/upload/examples/clientsidevalidation/defaultcs.aspx
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
http://yunzhu.iteye.com/blog/1116893

http://hi.baidu.com/2012betterman/item/48d2592c2d79059db73263a9

http://www.cnblogs.com/zorroLiu/archive/2011/08/31/2160858.html

http://mzhou.me/?p=95250
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值