上传文件到服务器例子,包括前端后台一整套

时间:2024-11-08 08:05:58
首先从前端开始:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script src="js/jquery-1.12."></script>
<script src="js/"></script>
<body>
	<form >
		选择一个文件:
		<input type="file" name="file"  />
		<br/><br/>
		<input  value="上传" type="button"/>
	</form>
	
	<div ></div>
</body>
<script type="text/javascript">

$("#uploadFile").click(function(){
	var formData = new FormData($("#upfile")[0]);
	//('file', ("upload").files[0]);
	$.ajax({
        url: '${}/uploadFile/upload',
        type: 'POST',
        cache: false,
        data: formData,
        processData: false,
        contentType: false
    }).done(function(res) {
        
    });
});
</script>
</html>
上面那个js中注掉的那行,是 直接定位到file那个标签,但是set方法在低版本的浏览器上不支持,会报错只供参考,注意file标签必须是在form里面,记得不能嵌套form,只能有一个form;一般form都是<form method="post" action="" enctype="multipart/form-data" ></form>;我上面例子只是精简了;

前端完成后到后端:
先配置一些参数:
(设置上传文件的大小和服务器地址):
#upload
 = 104857600
=http://192.168.102.11/test
需要引入的jar包

                 <dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId></groupId>
			<artifactId>guava</artifactId>
			<version>18.0</version>
		</dependency>
		<dependency>
		    <groupId>commons-httpclient</groupId>
		    <artifactId>commons-httpclient</artifactId>
		    <version>3.1</version>
		</dependency>
		<dependency>
		    <groupId></groupId>
		    <artifactId>wagon-webdav-jackrabbit</artifactId>
		    <version>2.4</version>
		</dependency>
		<dependency>
			<groupId>slide</groupId>
			<artifactId>slide-webdavlib</artifactId>
			<version>2.1</version>
		</dependency>




spring配置中需要加下面配置:
<!-- 引入配置文件中的参数 -->
	<context:property-placeholder location="classpath:" />
	<!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver -->
	<bean  class="">
		<property name="defaultEncoding" value="UTF-8"></property>
		<property name="maxUploadSize" value="50485760"></property>
		<property name="resolveLazily" value="true"></property>
	</bean>

	<!-- 对传入的url进行一些处理,这个<span style="font-family: Arial, Helvetica, sans-serif;">UploadFileUtils类所在路径需要根据你实际放置到项目的路径一致,这个类我下面提供了,建完这个类后别忘记把class中的路径替换掉</span>-->
	<bean class="">
		<property name="downloadUrl" value="${}"/>
	</bean>
(这个类主要是对config中的url参数的一些处理)
import .;



public class UploadFileUtils {

	public static String downloadUrl = null;

    /**
     * 绝对路径与相对路径转换
     */
    public static String addPrefix(String url) {
        // 本身就是绝对路径直接返回
        if (url == null || ("http://") || ("https://")) {
            return url;
        }
        return (downloadUrl, url);
    }

    public static String removePrefix(String url) {
        // 如果 url 不符合条件,直接返回
        if (url == null || !(downloadUrl)) {
            return url;
        }
        return (url, downloadUrl);
    }

    public void setDownloadUrl(String downloadUrl) {
         = downloadUrl;
    }
}
controller接收请求:
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;

/**
 * @author 
 *
 */
@Controller
@RequestMapping("/uploadFile")
public class UploadFile{

	@Autowired
	private UploadService uploadService;
	/**
	 * 需要在spring-mvc中配置MultipartFile相关信息,以及引进fileUpload的依赖
	 * @param multipartFile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/upload", method = )
	@ResponseBody
	public FileInfo upload(@RequestParam("file")MultipartFile multipartFile)throws Exception{
		
		FileInfo fileInfo = (multipartFile);
		return fileInfo;
	}
	
}
实体类,封装了一些属性,文件名,文件类型,相对地址,绝对地址
public class FileInfo {

	private String fileName;

    private String fileType;

    private String absoluteUrl;

    private String relativeUrl;

    private String fileSize;

    private String fileMd5;

    private String createAt;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		 = fileName;
	}

	public String getFileType() {
		return fileType;
	}

	public void setFileType(String fileType) {
		 = fileType;
	}

	public String getAbsoluteUrl() {
		return absoluteUrl;
	}

	public void setAbsoluteUrl(String absoluteUrl) {
		 = absoluteUrl;
	}

	public String getRelativeUrl() {
		return relativeUrl;
	}

	public void setRelativeUrl(String relativeUrl) {
		 = relativeUrl;
	}

	public String getFileSize() {
		return fileSize;
	}

	public void setFileSize(String fileSize) {
		 = fileSize;
	}

	public String getFileMd5() {
		return fileMd5;
	}

	public void setFileMd5(String fileMd5) {
		this.fileMd5 = fileMd5;
	}

	public String getCreateAt() {
		return createAt;
	}

	public void setCreateAt(String createAt) {
		 = createAt;
	}
    
    
}

然后到service中进行业务处理:
(业务处理接口)
import ;

import ;

public interface UploadService {

	/**
	 * 上传文件,返回链接
	 * @param multipartFile
	 * @return
	 */
	FileInfo uploadFile(MultipartFile multipartFile);

}

具体的实现类:
import static ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .MD5;
import ;
import ;

/**
 * 
 * @author 
 *
 */
@Service
public class UploadServiceImpl implements UploadService{
	
	@Value("${}")
    private String uploadUrl;

    @Value("webdav")
    private String uploadUsername;

    @Value("webdav")
    public String uploadPassword;
	
	@Override
	public FileInfo uploadFile(MultipartFile multipartFile) {
		
		//取到文件大小,如果超过指定范围的话就直接返回提醒错误
        long size = ();
        //获取文件名
        String fileName = ();
        // 获取文件后缀,即文件类型
        String fileExt = "";
        if ((".")) {
            fileExt = ((".") + 1).toLowerCase();
        }
        //设置MD5加密
        String fileMD5 = md5File(multipartFile);

        //拼接文件路径:/后缀/年/月/日/md5/filename
        String saveUrl = "/" + fileExt + new SimpleDateFormat("/yyyy/MM/dd/").format(new Date()) + fileMD5 + "/" + ();

        String location = null;
		try {
			location = saveFile(multipartFile, saveUrl);//保存文件操作
		} catch (Exception e) {
			();
		}

        FileInfo fileInfo = new FileInfo();
        (location);
        (saveUrl);
        fileInfo.setFileMd5(fileMD5);
        (fileName);
        ((size));
        (fileExt);
        (DateUtil.date2String(new Date(), DateUtil.DATE_TIME_FORMAT));
        return fileInfo;

	}
	
	//MD5加密
	private String md5File(MultipartFile multipartFile) {
        try {
            return MD5.md5(());
        } catch (IOException e) {
            ();
        }
        return null;
    }
	
	
	
	private String saveFile(MultipartFile file, String savePath) throws Exception {
        // 上传文件,到文件服务器,uploadUrl是在config中配好的,就是给uploadUrl赋值,如果不用那么麻烦的话可以直接把url放进去:upload("http://192.168.102.11/test", uploadUsername, uploadPassword, savePath, ());
    	upload(uploadUrl, uploadUsername/*那台服务器的用户名*/, uploadPassword/*那台服务器的密码*/, savePath, ());
        return append(uploadUrl, savePath);
        
    }
	
	
	public static void upload(String webDavServer, String webDavUser, String webDavPassword, String remotePath, byte[] bytes) throws IOException {

		if (!("/")) webDavServer += "/";
		
		//连接服务器
		HttpURL hrl = new HttpURL(webDavServer);
		(webDavUser, webDavPassword);

		WebdavResource wdr =  new WebdavResource(hrl);

		//make directory if need
		StringBuffer ssdir = new StringBuffer();
		// 去除最后一个文件名
		StringTokenizer t = new StringTokenizer((0, ("/")), "/");
		while(()){
			String sdir = ();
			(sdir+"/");
			(() + ssdir );
		}

		String remoteFile= () + remotePath;//拼成绝对地址
		boolean result = (remoteFile, bytes);//把文件写进去
		checkArgument(result, "文件上传出错");//false时会报错,true则为成功

		();//最后关闭连接

	}
	
	
	
    /**
     * 连接 URL
     * @param paths
     * @return
     */
    public static String append(String... paths) {
        List<String> pathList = (paths);
        PeekingIterator<String> iter = (());
        StringBuilder urlBuilder = new StringBuilder();
        while (()) {
            String current = ();
            (current);
            if (!()) {
                break;
            }
            if (("/") && ().startsWith("/")) {
                (() - 1);
            } else if (!("/") && !().startsWith("/")) {
                ("/");
            }
        }
        return ();
    }

}
所有的代码都已经在上面了,我已经测试过能上传成功,相应方法的注释页标在上面,希望你能运行成功;如果有什么问题可以留言给我,尽量能帮到你