最近在作文件上传,小文件到无所谓,可是一般情况下都是大文件所以经常会出outofmemory,自己写了个小程序,目前可以多线程上传,也可以通过c++客户端和c#客户端上传,附件里的程序是c++和c#的,大概想法就是把大文件切分成小文件每次上传2M直到文件结束,也可以扩展下支持断点续传
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.RequestContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
import java.io.*;
import java.util.*;
import java.net.URLDecoder;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
/**
* 服务器端
*/
public class UploadCFileServlet extends HttpServlet {
private Map map = null;
public void init() throws ServletException
{
super.init();
try {
map = new HashMap();
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public void destroy()
{
super.destroy();
try {
if(map != null)
{
map.clear();
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String reqSessionId = request.getHeader("Cookie");
// System.out.println("reqSessionId = "+reqSessionId);
String FileEnd = request.getHeader("FileEnd");
// System.out.println("FileEnd = "+FileEnd);
//true uploadfile is end ,false go on upload
boolean isEnd = false;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
File newFile = null;
try {
String path = this.getServletContext().getRealPath("/");
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if (FileUpload.isMultipartContent(requestContext)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(path));
// factory.setSizeThreshold(8096);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
try {
items = upload.parseRequest(request);
} catch (FileUploadException e1) {
System.out.println("文件上传发生错误" + e1.getMessage());
}
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem fileItem = (FileItem) it.next();
if (!fileItem.isFormField()) {
String fileName = URLDecoder.decode(fileItem.getName(), "utf-8");
System.out.println(fileItem.getFieldName() + " " + fileName + " " +fileItem.isInMemory() + " " +fileItem.getContentType() + " " +fileItem.getSize());
if (fileItem.getName() != null && fileItem.getSize() != 0) {
File fullFile = new File(fileName);
newFile = new File(path+"/sharefolder/" + fullFile.getName());
// if the file exists and the sessionid is also exists so add the file
if(reqSessionId !=null &&isExists(reqSessionId))
{
InputStream is = fileItem.getInputStream();
int length = is.available();
System.out.println("filitem length ="+length);
byte[] buffer = new byte[length];
is.read(buffer,0,length);
RandomAccessFile raf = new RandomAccessFile(newFile, "rw");
long fileLength = Long.valueOf(newFile.length()).longValue();
System.out.println("fileLength ="+fileLength);
raf.seek(fileLength);
raf.write(buffer);
raf.close();
is.close();
// if true uploadfile is end ,false go on upload
isEnd = Boolean.valueOf(FileEnd).booleanValue();
if(isEnd)
{
removeSessionId(reqSessionId);
}
}
// a new file is upload
else
{
try {
fileItem.write(newFile);
// if true uploadfile is end ,false go on upload
isEnd = Boolean.valueOf(FileEnd).booleanValue();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
out.println("200");
if(!isEnd)
{
if(reqSessionId == null)
{
HttpSession hs = request.getSession();
reqSessionId = hs.getId();
}
map.put(reqSessionId,newFile);
response.addHeader("Cookie",reqSessionId);
}
} catch (IOException e) {
out.println("400");
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
}
}
public boolean isExists(String sessionId)
{
if(map.get(sessionId) != null)
{
return true;
}
return false;
}
public void removeSessionId(String sessionId)
{
System.out.println("remove sessionId="+sessionId);
map.remove(sessionId);
System.out.println("map size="+map.size());
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.doPost(request,response);
}
}
//客户端
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;
public class testupload {
public static void main(String[] args) throws Exception {
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = "d:\\jdk150.ZH_cn.chm";
//String exsistingFileName ="e:\\[IBM.Lotus.Domino-Notes.7.0.1简体中文版全集].Lotus_Domino_Server_7.0.1_zh-CN_Windows.zip";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize, start;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
String urlString = "http://192.168.1.12/UploadCFileServlet";
String Cookie = null;
String FileEnd = null;
System.out.println("=====================================");
try {
//------------------ CLIENT REQUEST
long start1 = System.currentTimeMillis();
long end1 = 0;
FileInputStream fileInputStream = new FileInputStream(new File(
exsistingFileName));
bytesAvailable = fileInputStream.available();
System.out.println("bytesAvailable ===" + bytesAvailable);
bufferSize = 2 * 1024 * 1024;
buffer = new byte[bufferSize];
// read file and write it into form...
start = 0;
// bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int i = 0;
boolean flag = true;
while (flag) {
if (bytesAvailable > 0) {
int newAvailable = fileInputStream.available();
if (newAvailable < bufferSize) {
bufferSize = newAvailable;
buffer = new byte[bufferSize];
flag = false;
FileEnd = "true";
}
System.out.println("new available = " + newAvailable);
bytesAvailable = fileInputStream
.read(buffer, 0, bufferSize);
System.out.println("bytesRead ===" + bytesAvailable);
}
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
if (Cookie != null)
conn.setRequestProperty("Cookie", Cookie);
if (FileEnd != null)
conn.setRequestProperty("FileEnd", FileEnd);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos
.writeBytes("Content-Disposition: form-data; name=\"uploadfile\";"
+ " filename=\""
+ URLEncoder.encode(exsistingFileName, "utf-8")
+ "\"" + lineEnd);
dos.writeBytes(lineEnd);
// String str1 = new String(buffer);
// System.out.println("str1 ="+str1);
int length = buffer.length;
System.out.println("length =" + length);
dos.write(buffer, 0, bufferSize);
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
dos.flush();
dos.close();
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
Map headers = conn.getHeaderFields();
Set keys = headers.keySet();
for (String key : keys) {
String val = conn.getHeaderField(key);
System.out.println(key + " " + val);
if (key != null && key.equalsIgnoreCase("Cookie")) {
Cookie = val;
}
}
String str;
while ((str = inStream.readLine()) != null) {
System.out.println("Server response is: " + str);
System.out.println("");
}
inStream.close();
} catch (IOException ioex) {
System.out.println("From (ServerResponse): " + ioex);
}
System.out.println("=====================================");
}
fileInputStream.close();
end1 = System.currentTimeMillis();
System.out.println("upload times" + ((end1 - start1) / 1000)
+ " seconds.");
} catch (MalformedURLException ex) {
System.out.println("From ServletCom CLIENT REQUEST:" + ex);
} catch (IOException ioe) {
System.out.println("From ServletCom CLIENT REQUEST:" + ioe);
}
}
}
分享到:
相关推荐
包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。【适用人群】:适用...
包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。【适用人群】:适用...
2. **antlr-2.7.6.jar**: 用于创建解析器和编译器的开源库,支持多种编程语言,如Java、C#和C++。它提供了一种机制来定义语法规则,并自动生成相应的解析器代码。 3. **cglib-nodep-2.1_3.jar**: CGLIB是一个代码...
文件太大放服务器下载,请务必到电脑端资源详情查看然后下载
ssm旅游资源网站.zip
文件放服务器下载,请务必到电脑端资源详情查看然后下载
文件放服务器下载,请务必到电脑端资源详情查看然后下载
文件太大放服务器下载,请务必到电脑端资源详情查看然后下载
基于分片技术实现高性能区块链的Go源码和项目说明,是一个专为计算机、数学及电子信息等专业学生设计的毕业设计项目。该项目利用先进的区块链技术和分片机制,旨在解决传统区块链在大规模数据处理中的性能瓶颈问题。本项目通过引入分片技术,将区块链网络划分为多个较小的分片,每个分片独立处理一部分交易和数据。这种架构不仅提高了系统的并行处理能力,还显著提升了整体的交易吞吐量和网络性能。同时,项目还详细阐述了如何实现跨分片的数据同步与一致性保证,确保了系统的安全性和可靠性。此外,项目还包括完整的代码实现和详细的项目说明文档,为学习者提供了从理论到实践的全面指导。无论是区块链技术的初学者还是有一定基础的开发者,都可以通过这个项目深入了解分片技术的实现原理和应用方法。总的来说,这是一个集学习、实践与创新于一体的综合性项目,适合作为相关专业课程设计、期末大作业或毕业设计的优选题目。
福聚苑社区团购.zip
文件太大放服务器下载,请务必到电脑端资源详情查看然后下载
文件放服务器下载,请务必到电脑端资源详情查看然后下载
文件放服务器下载,请务必到电脑端资源详情查看然后下载
该单片机项目可作为课程设计和期末大作业或者毕设,项目完整,有原理图和代码,需要的自行下载即可!
文件放服务器下载,请务必到电脑端资源详情查看然后下载
java java小游戏,滚木块.zip学习资源代码
文件太大放服务器下载,请务必到电脑端资源详情查看然后下载
文件放服务器下载,请务必到电脑端资源详情查看然后下载
因文件较多,数据存放网盘,txt文件内包含下载链接及提取码,永久有效。失效会第一时间进行补充。样例数据及详细介绍参见文章:https://blog.csdn.net/T0620514/article/details/144224915