Java實(shí)現(xiàn)文件上傳的方法
本文實(shí)例為大家分享了Java實(shí)現(xiàn)文件上傳的具體代碼,具體內(nèi)容如下
1、java代碼:
package com.github.reston.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
@WebServlet("/AjaxUpload")
public class AjaxUpload extends HttpServlet{
@Override
public void init(ServletConfig config) throws ServletException{
// TODO Auto-generated method stub
super.init(config);
}
@Override
protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/html");
request.setCharacterEncoding("UTF-8");
boolean isMultipart=ServletFileUpload.isMultipartContent(request);
String basePath=getServletContext().getRealPath("/upload");
File baseDirectory=new File(basePath);
String filename="";
long start=0;
if(!baseDirectory.isDirectory()) baseDirectory.mkdirs();
if(isMultipart){
try{
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
@SuppressWarnings("unchecked") List<FileItem> fileItems=upload.parseRequest(request);
for(FileItem i:fileItems){
if(i.isFormField()){
String name=i.getFieldName();
String value=i.getString();
if(name.equals("start"))start=Long.parseLong(i.getString());
}
}
for(FileItem item:fileItems){
if(item.isFormField()) continue;
filename=item.getFieldName();
if(mkdir(basePath)){
File fileonserver=createFile(basePath,filename);
if(fileonserver.length()==0){
FileOutputStream fos=new FileOutputStream(fileonserver,true);
IOUtils.copy(item.getInputStream(),fos);
}
if(start>0){
FileOutputStream fos=new FileOutputStream(fileonserver,true);
IOUtils.copy(item.getInputStream(),fos);
}
PrintWriter pw=response.getWriter();
pw.write("{\"length\":\""+fileonserver.length()+"\"}");
pw.flush();
}
}
}catch(Exception e){
}
}
}
private File createFile(String path,String name) throws IOException{
File tmp=new File(path,name);
if(!tmp.exists()){
tmp.createNewFile();
}
return tmp;
}
private boolean mkdir(String path){
boolean result=true;
File tmp=new File(path);
if(!tmp.isDirectory()){
result=tmp.mkdirs();
}
return result;
}
}
2、java代碼:
var ajaxupload = function(e) {
/**
* e url method data success error
*/
var xmlhttprequest;
if (window.XMLHttpRequest) {
xmlhttprequest = new XMLHttpRequest();
if (xmlhttprequest.overrideMimeType) {
xmlhttprequest.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
var activeName = [ "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
for (var i = 0; i < activeName.length; i++) {
try {
xmlhttprequest = new ActiveXObject(activeName[i]);
break;
} catch (e) {
return;
}
}
}
if (xmlhttprequest == undefined || xmlhttprequest == null) {
alert("XMLHttpRequest對(duì)象創(chuàng)建失?。?!");
return;
} else {
this.xmlhttp = xmlhttprequest;
}
var file = document.getElementById(e.id);
if (this.xmlhttp != undefined && this.xmlhttp != null) {
e.method = e.method.toUpperCase();
if (e.method != "GET" && e.method != "POST") {
alert("HTTP的請(qǐng)求方法必須為GET或POST!!!");
return;
}
if (e.url == null || e.url == undefined) {
e.alert("HTTP的請(qǐng)求地址必須設(shè)置!");
return;
}
}
this.xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
var responseText = this.responseText;
var responseXML = this.reponseXML;
if (e.success == undefined || e.success == null) {
alert("沒(méi)有設(shè)置處理數(shù)據(jù)正確返回的方法");
alert("返回的數(shù)據(jù):" + responseText);
} else {
e.success(responseText, responseXML);
}
} else {
if (e.error == undefined || e.error == null) {
alert("沒(méi)有設(shè)置處理數(shù)據(jù)返回失敗的處理方法!");
alert("HTTP的響應(yīng)碼:" + this.status + ",響應(yīng)碼的文本信息:" + this.statusText);
} else {
e.error(this.status, this.statusText);
}
}
}
}
// var formhtm="<form id='output' enctype='multipart/form-data' ></form>";
var filename = getFileName(e.id);
this.xmlhttp.open(e.method, e.url, true);
var data = new FormData(document.getElementById("output"));
data.append("name", filename);
data.append("start", e.data.start);
data.append(filename, document.getElementById(e.id).files[0].slice(e.data.start, getFileSize(e.id)));
this.xmlhttp.send(data);
}
function getFileName(id) {
var path = document.getElementById(id).value
var pos1 = path.lastIndexOf('/');
var pos2 = path.lastIndexOf('\\');
var pos = Math.max(pos1, pos2);
return path.substring(pos + 1);
}
function getFileSize(id) {
return document.getElementById(id).files[0].size;
}
3、html代碼:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input type="file" name="upload" id="upload" value="上傳"/><span>請(qǐng)選擇要上傳的文件(小于1G)</span>
<input type="button" value="上傳" onclick="test();"/>
<form id="output" enctype="multipart/form-data" ></form>
<script>
function test(){
ajaxupload({
id : "upload",
url : "/PCC/reston/AjaxUpload",
method : "POST",
data : {start:0},
success : function(e) {
var l=JSON.parse(e).length;
ajaxupload({
id : "upload",
url : "/PCC/reston/AjaxUpload",
method : "POST",
data : {start:l},
success : function(e) {
},
error : function(e) {
console.log(e);
}
});
},
error : function(e) {
console.log(e);
}
});
}
</script>
</body>
</html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家學(xué)習(xí)java程序設(shè)計(jì)有所幫助。
相關(guān)文章
詳解Java數(shù)組的一維和二維講解和內(nèi)存顯示圖
這篇文章主要介紹了Java數(shù)組的一維和二維講解和內(nèi)存顯示圖,數(shù)組就相當(dāng)于一個(gè)容器,存放相同類型數(shù)據(jù)的容器。而數(shù)組的本質(zhì)上就是讓我們能 "批量" 創(chuàng)建相同類型的變量,需要的朋友可以參考下2023-05-05
Java8 CompletableFuture 異步執(zhí)行操作
CompletableFuture是java8提供的基于異步操作的封裝,日常開(kāi)發(fā)中經(jīng)常會(huì)用到,接下來(lái)通過(guò)本文給大家介紹Java8 CompletableFuture 異步執(zhí)行操作,感興趣的朋友一起看看吧2021-06-06
教你如何精準(zhǔn)統(tǒng)計(jì)出你的接口"QPS"
今天小編就為大家分享一篇關(guān)于QPS的精準(zhǔn)計(jì)算方法,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2021-08-08
java數(shù)據(jù)結(jié)構(gòu)圖論霍夫曼樹(shù)及其編碼示例詳解
這篇文章主要為大家介紹了java數(shù)據(jù)結(jié)構(gòu)圖論霍夫曼樹(shù)及其編碼示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2021-11-11
JavaWeb實(shí)現(xiàn)簡(jiǎn)單上傳文件功能
這篇文章主要為大家詳細(xì)介紹了JavaWeb實(shí)現(xiàn)簡(jiǎn)單上傳文件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06
Java中使用LocalDate根據(jù)日期來(lái)計(jì)算年齡的實(shí)現(xiàn)方法
這篇文章主要介紹了Java中使用LocalDate根據(jù)日期來(lái)計(jì)算年齡的實(shí)現(xiàn)方法,需要的朋友可以參考下2018-01-01
Java中四種9*9乘法表的實(shí)現(xiàn)方式(附代碼)
這篇文章主要介紹了Java中四種9*9乘法表的實(shí)現(xiàn)方式(附代碼),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

