服务器之家

服务器之家 > 正文

Java实现文件上传的方法

时间:2020-05-04 13:54     来源/作者:CCTV七月

本文实例为大家分享了Java实现文件上传的具体代码,具体内容如下

1、java代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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对象创建失败!!");
  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的请求方法必须为GET或POST!!!");
   return;
  }
  if (e.url == null || e.url == undefined) {
   e.alert("HTTP的请求地址必须设置!");
   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("没有设置处理数据正确返回的方法");
     alert("返回的数据:" + responseText);
    } else {
     e.success(responseText, responseXML);
    }
   } else {
    if (e.error == undefined || e.error == null) {
     alert("没有设置处理数据返回失败的处理方法!");
     alert("HTTP的响应码:" + this.status + ",响应码的文本信息:" + 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代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!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>请选择要上传的文件(小于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>

以上就是本文的全部内容,希望对大家学习java程序设计有所帮助。

标签:

相关文章

热门资讯

沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
超A是什么意思 你好a表达的是什么
超A是什么意思 你好a表达的是什么 2019-06-06
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
返回顶部