使用js来实现文件上传-tmp文件

使用js来实现文件上传-tmp文件

我在CSDN看到的一篇技术博客,挺有用的,转发地址:https://blog.csdn.net/andywei147/article/details/80636539,在此先感谢博主的分享。现在分享给大家:

一、前端HTML部分

<div class='main'>

<input type='file' class='filebutton' style='display:none' onchange='fileSelected()' /> <br>

<button class="upload" onclick='openFileDialog()' > 选择文件上传 </button>

<div class="img">

</div>

</div>

二、js部分

//点击普通按钮,打开文件选择框

function openFileDialog()

{

$(".filebutton").click();

}

//选择一个文件时onchange时间被触发

function fileSelected()

{

var fbutton = $(".filebutton")[0];//dom元素

//读取文件

var reader = new FileReader();

reader.onload = function(e)

{

var dataURL = e.target.result;//'data:image/jpeg;base64,/9j/4AAQSk...(base64编码)...'

//alert(data);

var htmlImg = "<img src = '" + dataURL + "'/>";

$(".img").html(htmlImg);

}

var file = fbutton.files[0];

reader.readAsDataURL(file);

startFileUpload(file);

}

//开始上传

function startFileUpload(file)

{

var uploadURL = "FileUploadServer";

//手工构造一个form对象

var formData = new FormData();

formData.append("file" , file);// 'file' 为HTTP Post里的字段名, file 对浏览器里的File对象

//手工构造一个请求对象,用这个对象发送表单数据

//设置 progress, load, error, abort 4个事件处理器

var request = new XMLHttpRequest();

request.upload.addEventListener("progress" , window.evt_upload_progress , false);

request.addEventListener("load", window.evt_upload_complete, false);

request.addEventListener("error", window.evt_upload_failed, false);

request.addEventListener("abort", window.evt_upload_cancel, false);

request.open("POST", uploadURL ); // 设置服务URL

request.send(formData); // 发送表单数据

}

window.evt_upload_progress = function(evt)

{

if(evt.lengthComputable)

{

var progress = Math.round(evt.loaded * 100 / evt.total);

console.log("上传进度" + progress);

}

};

window.evt_upload_complete = function (evt)

{

if(evt.loaded == 0)

{

console.log ("上传失败!");

}

else

{

console.log ("上传完成!");

var response = JSON.parse(evt.target.responseText);

console.log (response);

}

};

window.evt_upload_failed = function (evt)

{

console.log ("上传出错");

};

window.evt_upload_cancel = function (evt)

{

console.log( "上传中止!");

};

三、后端部分,需要两个jar包的支持,他们分别是:commons-fileupload-1.3.1.jar commons-io-2.4.jar

package my.fileUpload;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.UUID;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;

import org.apache.commons.fileupload.FileItemStream;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.fileupload.util.Streams;

import org.json.JSONObject;

public class FileUploadServer extends HttpServlet {

File tmpDir;//文件保存的临时目录

@Override

public void init() throws ServletException {

System.out.println("初始化");

File webRoot = new File(getServletContext().getRealPath("/"));

tmpDir = new File(webRoot , "upload");

if(!tmpDir.exists()) tmpDir.mkdirs();

}

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request , response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

System.out.println("进入");

int error = 0;

String reason = "OK";

String data = ;

try {

data = doUpload(request , response);

} catch (Exception e) {

error = -1;

reason = e.getMessage();

// TODO Auto-generated catch block

e.printStackTrace();

}

JSONObject jreq = new JSONObject();

jreq.put("error", error);

jreq.put("reason", reason);

if(data != null) jreq.put("data", data);

response.setCharacterEncoding("utf-8");

response.setContentType("text/plain");

PrintWriter out = response.getWriter();

out.write(jreq.toString(2));

}

private String doUpload(HttpServletRequest request, HttpServletResponse response) throws Exception

{

String result = ;

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if(!isMultipart)

throw new Exception("请求编码必须为: multipart/form-data !");

request.setCharacterEncoding("utf-8");

ServletFileUpload upload = new ServletFileUpload();

FileItemIterator iter = upload.getItemIterator(request);

while(iter.hasNext())

{

//表单域

FileItemStream item = iter.next();

String fieldName = item.getFieldName();

InputStream fieldStream = item.openStream();

if(item.isFormField())

{

//普通表单域直接读取

String fieldValue = Streams.asString(fieldStream , "utf-8");

System.out.println("表单域:" + fieldName + "=" + fieldValue);

}

else

{

String realName = item.getName();//原始文件名

//文件的后缀名

String suffix = realName.substring(realName.lastIndexOf(".")+1);

System.out.println("文件名:" + realName + "....." + "后缀名:" + suffix);

//创建已个临时文件名

String s = UUID.randomUUID().toString();

String s2 = s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);

s2 = s2.toUpperCase();

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");

String dateStr = sdf.format(new Date());

String fileName = dateStr +"-" + s2 + "." + suffix;

result = fileName;

System.out.println("文件名:" + fileName);

File file = new File(tmpDir , fileName);

long fileSsize = 0;//文件大小

System.out.println("===========文件开始上传=============");

//从FieldStream读取数据,保存到目标文件

file.getParentFile().mkdirs();

FileOutputStream fileStream = new FileOutputStream(file);

try

{

byte[] buf = new byte[1024];

while(true)

{

int n = fieldStream.read(buf);

if(n < 0) break;

if(n == 0) continue;

fileStream.write(buf, 0, n);

fileSsize += n;

}

}finally

{

fileStream.close();

fieldStream.close();

}

System.out.println("上传完成!");

}

}

return result;

}

}

大家有问题都可以讨论,一起进步,一起成长,谢谢大家

推荐阅读