1.前端

(1)依赖文件:

    <link type="text/css" rel="stylesheet" href="~/Content/plupload_2_1_2/jquery-ui.min.css" media="screen" />
<link type="text/css" rel="stylesheet" href="~/Content/plupload_2_1_2/jquery.ui.plupload/css/jquery.ui.plupload.css" media="screen" />
<script type="text/javascript" src="~/Content/plupload_2_1_2/jquery.js" charset="UTF-8"></script>
<script type="text/javascript" src="~/Content/plupload_2_1_2/jquery-ui.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="~/Content/plupload_2_1_2/plupload.full.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="~/Content/plupload_2_1_2/jquery.ui.plupload/jquery.ui.plupload.min.js" ></script>
<script type="text/javascript" src="~/Content/plupload_2_1_2/zh_CN.js" charset="UTF-8"></script>

(2)HTML

    <form id="uploader">
<input type="text" name="filename" value="" />
</form>

(3)js

   <script type="text/javascript">
//文件名不能相同
$(function () {
$("#uploader").plupload({
// General settings
runtimes: 'gears,flash,silverlight,browserplus,html5',
url: '/upload/plupload',
max_file_size: '6079mb',
max_file_count: 20,
chunk_size: '2048kb',
unique_names: false,
init: { // Resize images on clientside if we can
//resize: { width: 320, height: 240, quality: 90 },
rename: false, // 是否重命名文件
sortable: true, // Sort files
dragdrop: true, //启用文件到小部件能够拖放(操作)(目前唯一HTML5支持)
filters: [
{ title: "Image files", extensions: "jpg,gif,png,txt,sql" },
{ title: "music", extensions: "avi,mp4,mp3,exe,zip" }
],
views: {
list: true,
thumbs: true, // Show thumbs
active: 'thumbs'
},
// Flash settings
flash_xap_url: '~/Content/upload/js/Moxie.xap',
// Silverlight settings
silverlight_xap_url: '~/Content/upload/js/Moxie.xap',
BeforeUpload: function (uploader, file) {
//alert(123)
//var $li = $('#uploader_filelist li').hasClass('plupload_file')[0]
//var value = $($li).find('div.plupload_file_name').attr('title')
//alert($li)
},
QueueChanged: function () {
var $li = $('#uploader_filelist li')
console.log($li)
},
FileUploaded: function (uploader, file, responseObject) {
//console.log(responseObject)
//alert(curDirID)
//initData(responseObject.response.curDirId)
$.ajax({
url: '/Cloudpan/GetCurdir',
type: 'post',
success: function (id) {
initData(id)
}
})
}
}
});
});
</script>

2.后台

  后台可以使用FileInputStream的构造方法追加文件内容。plupload使用“multipart/form-data”这种表单上传文件,其中每一个分块会发出一次请求,表单中有两个字段,分别是“chunk”和“chunks”,其中“chunk”是当前正在处理的文件分块的序号(从0开始计数),而“chunks”则是文件的分块总数。

(1).net

  asp.net MVC【有bug】

/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public JsonResult plupload(string name)
{
string msg = string.Empty;
string strchunk = Request["chunk"];
string strchunks = Request["chunks"];
int chunk = ;
int chunks = ;
int.TryParse(strchunk, out chunk);
int.TryParse(strchunks, out chunks); foreach (string upload in Request.Files)
{
if (upload != null && upload.Trim() != "")
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Temp\\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
System.Web.HttpPostedFileBase postedFile = Request.Files[upload];
string filename1 = Path.GetFileName(postedFile.FileName);
string filename = name; string newFileName = filename;
if (chunks>)
{
newFileName = chunk + "_" + filename;
}
string fileNamePath = path + newFileName;
postedFile.SaveAs(fileNamePath); if (chunks> && chunk + == chunks)
{
using (FileStream fsw = new FileStream(path + filename, FileMode.Create, FileAccess.Write))
{
BinaryWriter bw = new BinaryWriter(fsw);
// 遍历文件合并
for (int i = ; i < chunks; i++)
{
bw.Write(System.IO.File.ReadAllBytes(path + i.ToString() + "_" + filename));
bw.Flush();
}
} } }
}
return Json(new { jsonrpc = "2.0", result = "", id = "id" }); }

(2)servlet

config.properties:

uploadPath=/upload/images
package cn.getword.servlet;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils; 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 java.io.*;
import java.util.*; @WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload/plupload.do"})
public class FileUploadServlet extends HttpServlet {
String uploadPath;
private static final ResourceBundle bundle = ResourceBundle.getBundle( "config" ); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding( "UTF-8" );
Integer chunk = null; /* 分割块数 */
Integer chunks = null; /* 总分割数 */
String tempFileName = null; /* 临时文件名 */
String newFileName = null; /* 最后合并后的新文件名 */
BufferedOutputStream outputStream = null; /* System.out.println(FileUtils.getTempDirectoryPath()); */
uploadPath = request.getServletContext().getRealPath( bundle.getString( "uploadPath" ) );
File up = new File( uploadPath );
if ( !up.exists() )
{
up.mkdir();
} if ( ServletFileUpload.isMultipartContent( request ) )
{
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold( 1024 );
/* factory.setRepository(new File(repositoryPath));// 设置临时目录 */
ServletFileUpload upload = new ServletFileUpload( factory );
upload.setHeaderEncoding( "UTF-8" );
/* upload.setSizeMax(5 * 1024 * 1024);// 设置附件最大大小,超过这个大小上传会不成功 */
List<FileItem> items = upload.parseRequest( request );
for ( FileItem item : items ){
if ( item.isFormField() ) /* 是文本域 */
{
if ( item.getFieldName().equals( "name" ) )
{
tempFileName = item.getString();
/* System.out.println("临时文件名:" + tempFileName); */
} else if ( item.getFieldName().equals( "chunk" ) )
{
chunk = Integer.parseInt( item.getString() );
/* System.out.println("当前文件块:" + (chunk + 1)); */
} else if ( item.getFieldName().equals( "chunks" ) )
{
chunks = Integer.parseInt( item.getString() );
/* System.out.println("文件总分块:" + chunks); */
}
} else { /* 如果是文件类型 */
if ( tempFileName != null )
{
String chunkName = tempFileName;
if ( chunk != null )
{
chunkName = chunk + "_" + tempFileName;
}
File savedFile = new File( uploadPath, chunkName );
item.write( savedFile );
}
}
} // UUID+'.'+后缀名
newFileName = UUID.randomUUID().toString().replace( "-", "" )
.concat( "." )
.concat( FilenameUtils.getExtension( tempFileName ) );
if ( chunk != null && chunk + 1 == chunks )
{
outputStream = new BufferedOutputStream(
new FileOutputStream( new File( uploadPath, newFileName ) ) );
/* 遍历文件合并 */
for ( int i = 0; i < chunks; i++ )
{
File tempFile = new File( uploadPath, i + "_" + tempFileName );
byte[] bytes = FileUtils.readFileToByteArray( tempFile );
outputStream.write( bytes );
outputStream.flush();
tempFile.delete();
}
outputStream.flush();
}
Map<String, Object> m = new HashMap<String, Object>();
m.put( "status", true );
m.put( "fileUrl", bundle.getString( "uploadPath" ) + "/"
+ newFileName );
response.getWriter().write( JSON.toJSONString( m ) );
} catch ( FileUploadException e ) {
e.printStackTrace();
Map<String, Object> m = new HashMap<String, Object>();
m.put( "status", false );
response.getWriter().write( JSON.toJSONString( m ) );
} catch ( Exception e ) {
e.printStackTrace();
Map<String, Object> m = new HashMap<String, Object>();
m.put( "status", false );
response.getWriter().write( JSON.toJSONString( m ) );
} finally {
try {
if ( outputStream != null )
outputStream.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
} } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/views/student/uploadFile.jsp").forward(request, response);
}
}

servlet

  注意:

> request.getServletContext().getRealPath(virtualPath);  将虚拟路径转化成物理路径。
> ResourceBundle bundle = ResourceBundle.getBundle( "config" );
读取src下的config.properties文件。例如:file.config对应的文件为file包下config.properties文件

最新文章

  1. Python递归报错:RuntimeError: maximum recursion depth exceeded in comparison
  2. php 文件锁
  3. Spring对Quartz的封装实现简单需注意事项
  4. WDCP安装并配置php5.4和mongodb
  5. [原创]java WEB学习笔记70:Struts2 学习之路-- struts2拦截器源码分析,运行流程
  6. 数据库(MSSQLServer,Oracle,DB2,MySql)常见语句以及问题
  7. 单元测试React
  8. point类型&#183;
  9. python ——面向对象进阶
  10. nginx在 window下 自动退出 php-cgi
  11. 【Alpha】阶段总结报告
  12. [COGS 2258][HZOI 2015]复仇的序幕曲
  13. PHP----------一群猴子排成一圈,按1,2,...,n依次编号。
  14. iOS - Xcode项目统计总代码行数
  15. 5.10 C++内存管理操作符重载
  16. AT&amp;T汇编格式
  17. 02 workerman之GatewayWorker简单的demo 实现两端发送消息
  18. ZOJ 2770 差分约束+SPFA
  19. 剑指offer-顺时针打印矩阵-二维数组
  20. Http的响应结构

热门文章

  1. Mybatis的输出结果封装
  2. Linux 编写安全巡检脚本
  3. 【NOIP 2009】靶形数独
  4. thrift 通信的使用 /安装
  5. 80C51单片机介绍
  6. Xshell添加快捷按钮
  7. Photoshop入门教程(四):混合模式
  8. springMvc使用restful风格
  9. spring boot 启动时运行代码(2)ApplicationListener
  10. MySQL之concat以及group_concat的用法