用js来实现文件上传

  • 时间:2018-06-23 23:39 作者:goonmydream 来源:goonmydream 阅读:701
  • 扫一扫,手机访问
摘要:我在CSDN看到的一篇技术博客,挺有使用的,转发地址:https://blog.csdn.net/andywei147/article/details/80636539,在此先感谢博主的分享。现在分享给大家:一、前台HTML部分 class='main'> 选择文件上传

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

一、前台HTML部分

class='main'>

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

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

class="img">

二、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").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;

}

}

大家有问题都能探讨,一起进步,一起成长,谢谢大家

  • 全部评论(0)
最新发布的资讯信息
【系统环境|windows】字节跳动前台面试题解析:盛最多水的容器(2021-03-20 21:27)
【系统环境|windows】DevOps敏捷60问,肯定有你想理解的问题(2021-03-20 21:27)
【系统环境|windows】字节跳动最爱考的前台面试题:JavaScript 基础(2021-03-20 21:27)
【系统环境|windows】JavaScript 的 switch 条件语句(2021-03-20 21:27)
【系统环境|windows】解决 XML 数据应用实践(2021-03-20 21:26)
【系统环境|windows】20个编写现代CSS代码的建议(2021-03-20 21:26)
【系统环境|windows】《vue 3.0探险记》- 运行报错:Error:To install them, you can run: npm install --save core-js/modules/es.arra...(2021-03-20 21:24)
【系统环境|windows】浅谈前台可视化编辑器的实现(2021-03-20 21:24)
【系统环境|windows】产品经理入门迁移学习指南(2021-03-20 21:23)
【系统环境|windows】初识webRTC(2021-03-20 21:23)
血鸟云