Then I hope to take advantage of the program when needed these files to the server ( the server side I have a CRUD file permissions )
I want to use HttpClient4 mimic pages multipart / form-data to upload , but always go wrong.
I hope the experts can help us to see , very grateful .
local ( client ) code :
Test.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.fang.util.UploadUtil;
/**
* @time 2013-10-21
*/
public class Test {
public static void main(String[] args){
List<File> filelist = new ArrayList<File>();
filelist.add(new File("c:\\aaa.jpg"));
filelist.add(new File("c:\\bbb.txt"));
//filelist.add(new File("c:\\ccc.avi"));
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:8080/test.jsp");
UploadUtil.upload(post, filelist);
try {
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
entity.consumeContent();
} catch (Exception e) {
e.printStackTrace();
}
}
}
UploadUtil.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
/**
* @time 2013-10-21
*/
public class UploadUtil {
private static Log log = LogFactory.getLog(UploadUtil.class);
public static void upload(HttpPost post,List<File> files){
String boundary = "---------------------------test";
post.addHeader("Content-Type", "multipart/form-data; boundary="+boundary);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
String fullBoundary = "\r\n--"+boundary + "\r\n";
for(File file : files){
os.write(fullBoundary.getBytes());
os.write("Content-Disposition: form-data; name=\"uploadFile\"; filename=\"".getBytes());
os.write(file.getName().getBytes());
os.write("\"\r\n".getBytes());
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int total = 0;
int length = 0;
while((length=fis.read(b))!=-1){
os.write(b, 0, length);
total += length;
}
System.out.println("File name:"+file.getName());
System.out.println("File size:"+total);
System.out.println("================");
fis.close();
os.write("\r\n".getBytes());
}
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
HttpEntity entity = new InputStreamEntity(is , is.available());
post.setEntity(entity);
} catch (IOException e) {
log.error("设置上传的文件时出错",e);
}
}
}
server side :
test.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="org.apache.commons.fileupload.servlet.*"%>
<%@page import="org.apache.commons.fileupload.disk.*"%>
<%@page import="org.apache.commons.fileupload.*"%>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
System.out.println(isMultipart);
if(isMultipart){
try {
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024*2);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(fileSize!=null?fileSize:1024*1024*10);
upload.setSizeMax(-1);
upload.setHeaderEncoding("UTF-8");
List<FileItem> itemlist = upload.parseRequest(req);
for(FileItem item:itemlist){
System.out.println(item.getFieldName()+":"+item.getName()+":"+item.getSize());
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
%>
exception appears as:
org.apache.commons.fileupload.FileUploadException: Stream ended unexpectedly
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:381)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
I hope you can help experienced look
------ Solution --------------------------- -----------------
done such examples , but using jdk native HttpURLConnection. Background using the struts2 action but the struts2 file parsing is using commons-fileUpload 's . Transfer file's code is so
public class HttpURLConnectionUploadFileTest {
private static DataOutputStream ds;//用数据输出流可以直接writeBytes字符串
private static String boundary = "****";//分隔符随意
public static void main(String[] args) throws Exception {
HttpURLConnection conn = (HttpURLConnection) new URL(
"http://localhost:8080/Demo/fileUpload.action")
.openConnection();
setConnection(boundary, conn);
ds=new DataOutputStream(conn.getOutputStream());
//这里就是测试连续上传文件,我这里是用for循环传同一个文件楼主可以多次调用writeFile传//不同的文件
for(int i=0;i<4;i++){
writeFile(new File("e:/","ReplayParser.exe"),"files");
}
ds.writeBytes("--" + boundary + "--\r\n");
ds.flush();
ds.close();
conn.disconnect();
}
//这个是写文件的,根据浏览器传文件时的网络数据完全模拟一样的输出到服务端
private static void writeFile(File file,String inputName)
throws IOException, FileNotFoundException {
String fileName=URLEncoder.encode(file.getName(),"utf-8");
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\""+inputName+"\"; filename=\""+fileName+"\"\r\n");
ds.writeBytes("Content-Type: "+URLConnection.guessContentTypeFromName(fileName)+"\r\n\r\n");
FileInputStream fis=new FileInputStream(file);
byte[] b=new byte[1024];
int i=-1;
while((i=fis.read(b))!=-1){
ds.write(b, 0, i);
}
ds.writeBytes("\r\n");
fis.close();
}
private static void setConnection(String boundary, HttpURLConnection conn)
throws ProtocolException {
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
/**
* 告诉HttpUrlConnection,我们需要采用流方式上传数据,无需本地缓存数据。
* HttpUrlConnection默认是将所有数据读到本地缓存,然后再发送给服务器,
* 这样上传大文件时就会导致内存溢出。
*/
conn.setChunkedStreamingMode(1024);//这句话传文件时很重要
}
}
background using struts2 , of course, your landlord can also be replaced commons-fileUpload wording , struts2 interior also use commons-fileUpload so struts2 can upload the same success commons-fileUpload possible
public class FileUploadAction extends ActionSupport {
private List<File> files;
private List<String> filesFileName;
@Override
public String execute() throws Exception {
for(int i=0;i<files.size();i++){
files.get(i).renameTo(new File("F:/",i+filesFileName.get(i)));
}
return SUCCESS;
}
public List<File> getFiles() {
return files;
}
public void setFiles(List<File> files) {
this.files = files;
}
public List<String> getFilesFileName() {
return filesFileName;
}
}
------ For reference only ---------------------------------- -----
yes, this is what I wrote this program reference page.
http://www.pc6.com/infoview/Article_50285.html
hope you are able to find time to look to solve the problems about the younger , thank
------ For reference only ------------------ ---------------------
fis.close ();
commented try
------ For reference only ------------------------------ ---------
no effect.
------ For reference only -------------------------------------- -
you always have problems , can talk about specifically what the problem is
------ For reference only ----------------- ----------------------
I
String fullBoundary = "\r\n--"+boundary + "\r\n";
modified
String fullBoundary = "\r\n--"+boundary;
After
exception is not thrown , but still no way the server receives the file.
List
------ For reference only ------------------ ---------------------
is thrown back .
------ For reference only -------------------------------------- -
here are examples:
Java files chunked upload client source code
Java files chunked upload server source code
- ---- For reference only ---------------------------------------
< br />
very grateful , but you made a mistake,
This routine does not block a file upload,
but mimic a multipart / form-data in form upload several files simultaneously , and then the server receives . .
------ For reference only -------------------------------------- -
------ For reference only ---------------------------------- -----
very grateful , but you made a mistake,
This routine does not block a file upload,
but mimic a multipart / form-data in form upload several files simultaneously , and then the server receives . . kind.
also give you an example of this , but is divided into multiple blocks. You can ignore the multi-block business , we can see a how to deal with.
------ For reference only -------------------------------------- -
top of it, nobody feels the forum after work . .
------ For reference only -------------------------------------- -
Thank 12L, buttoned up.
control of your code,
Content-Type was originally just a little behind the \ r \ n
silent dead.
没有评论:
发表评论