<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>
<form id="uploader">
<input type="text" name="filename" value="" />
</form>
后台可以使用FileInputStream的构造方法追加文件内容。plupload使用“multipart/form-data”这种表单上传文件,其中每一个分块会发出一次请求,表单中有两个字段,分别是“chunk”和“chunks”,其中“chunk”是当前正在处理的文件分块的序号(从0开始计数),而“chunks”则是文件的分块总数。
asp.net MVC【有bug】
///
///
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" });
}
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文件
手机扫一扫
移动阅读更方便
你可能感兴趣的文章