javahttp上传文件到
文件从本地到服务器的功能,其实是为了解决目前浏览器不支持获取本地文件全路径。不得已而想到上传到服务器的固定目录,从而方便项目获取文件,进而使程序支持EXCEL批量导入数据。
java中文件上传到服务器的指定路径的代码:
在前台界面中输入:
<form method="post" enctype="multipart/form-data" action="../manage/excelImport.do">
请选文件:<input type="file" name="excelFile">
<input type="submit" value="导入" onclick="return impExcel();"/>
</form>
action中获取前台传来数据并保存
/**
* excel 导入文件明颂
* @return
* @throws IOException
*/
@RequestMapping("/usermanager/excelImport.do")
public String excelImport(
String filePath,
MultipartFile excelFile,HttpServletRequest request) throws IOException{
log.info("<<悉孙<<<<action:{} Method:{} start>>>>>>","usermanager","excelImport" );
if (excelFile != null){
String filename=excelFile.getOriginalFilename();
String a=request.getRealPath("u/cms/www/201509");
SaveFileFromInputStream(excelFile.getInputStream(),request.getRealPath("u/cms/www/201509"),filename);//保存到服激陆郑务器的路径
}
log.info("<<<<<<action:{} Method:{} end>>>>>>","usermanager","excelImport" );
return "";
}
/**
* 将MultipartFile转化为file并保存到服务器上的某地
*/
public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException
{
FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);
System.out.println("------------"+path + "/"+ savefile);
byte[] buffer =new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((byteread=stream.read(buffer))!=-1)
{
bytesum+=byteread;
fs.write(buffer,0,byteread);
fs.flush();
}
fs.close();
stream.close();
}
‘贰’ java用户HTTPURLConnection 上传文件过程是先把文件写入流中,然后上传吗,可以边度边传吗
那你就别用这种简单流去发送,你把你数据分包,用包数据去传
‘叁’ http如何实现同时发送文件和报文(用java实现)
你用的servlet还是别的框架?
选POST
选form-data
选body
选File
选文件
Send
// commonsfileupload组件的情况下,servlet接收的数据只能是type=file表单元素类型,那么获取type=text类型,就可以使用parseRequest(request)来获取list,fileitem,判断isFormField,为true非file类型的。就可以处理了。下面是处理的部分代码:
DiskFileItemFactoryfactory=newDiskFileItemFactory();factory.setSizeThreshold(1024*1024);
Stringdirtemp="c:";
Filefiledir=newFile(dirtemp+"filetemp");
Stringstr=null;if(!filedir.exists())filedir.mkdir();factory.setRepository(filedir);
ServletFileUploapload=newServletFileUpload(factory);
Listlist=upload.parseRequest(request);for(
inti=0;i<list.size();i++)
{
FileItemitem=(FileItem)list.get(i);
if(item.isFormField()){
System.out.println(item.getString());
}else{
Stringfilename=item.getName();
item.write(newFile(request.getRealPath(dir),filename));
}
}
‘肆’ 如何使用java实现基于Http协议的大文件传输
虽然在JDK的java.net包中已经提供了访问HTTP协议的基本功能,但是对于大部分应用程序来说,JDK库本身提供的功能还不够丰富和灵活。HttpClient是ApacheJakartaCommon下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。以下是简单的post例子:Stringurl="bbslogin2.php";PostMethodpostMethod=newPostMethod(url);//填入各个表单域的值NameValuePair[]data={newNameValuePair("id","youUserName"),newNameValuePair("passwd","yourPwd")};//将表单的值放入postMethod中postMethod.setRequestBody(data);//执行postMethodintstatusCode=httpClient.executeMethod(postMethod);//HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发//301或者302if(statusCode==HttpStatus.SC_MOVED_PERMANENTLY||statusCode==HttpStatus.SC_MOVED_TEMPORARILY){//从头中取出转向的地址HeaderlocationHeader=postMethod.getResponseHeader("location");Stringlocation=null;if(locationHeader!=null){location=locationHeader.getValue();System.out.println("Thepagewasredirectedto:"+location);}else{System.err.println("Locationfieldvalueisnull.");}return;}详情见:/developerworks/cn/opensource/os-httpclient/
‘伍’ java客户端怎么把本地的文件上传到服务器
String realpath = ServletActionContext.getServletContext().getRealPath("/upload") ;//获取服务器路径
String[] targetFileName = uploadFileName;
for (int i = 0; i < upload.length; i++) {
File target = new File(realpath, targetFileName[i]);
FileUtils.File(upload[i], target);
//这是一个文件复制类File()里面就是IO操作,如果你不用这个类也可以自己写一个IO复制文件的类
}
其中private File[] upload;// 实际上传文件
private String[] uploadContentType; // 文件的内容类型
private String[] uploadFileName; // 上传文件名
这三个参数必须这样命名,因为文件上传控件默认是封装了这3个参数的,且在action里面他们应有get,set方法
‘陆’ java怎么实现上传文件到服务器
common-fileupload是jakarta项目组开发的一个功能很强大的上传文件组件
下面先介绍上传文件到服务器(多文件上传):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB2312";
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置允许用户上传文件大小,单位:字节,这里设为2m
fu.setSizeMax(2*1024*1024);
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath("c://windows//temp");
//开始读取上传信息
List fileItems = fu.parseRequest(request);
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();
//正则匹配,过滤路径取文件名
String regExp=".+////(.+)$";
//过滤掉的文件类型
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type");
}
}
try{
//保存上传的文件到指定的目录
//在下文中上传文件至数据库时,将对这里改写
item.write(new File("d://" + m.group(1)));
out.print(name+" "+size+"");
}
catch(Exception e){
out.println(e);
}
}
else
{
throw new IOException("fail to upload");
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}
现在介绍上传文件到服务器,下面只写出相关代码:
以sql2000为例,表结构如下:
字段名:name filecode
类型: varchar image
数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");
代码如下:
。。。。。。
try{
这段代码如果不去掉,将一同写入到服务器中
//item.write(new File("d://" + m.group(1)));
int byteread=0;
//读取输入流,也就是上传的文件内容
InputStream inStream=item.getInputStream();
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close();
out.println(name+" "+size+" ");
}
。。。。。。
这样就实现了上传文件至数据库
‘柒’ Java客户端通过Http发送POST请求上传文件
要按http的multi-part上传的。接收端,再按multi-part解析成文件流
‘捌’ java 如何实现 http协议传输
Java 6 提供了一个轻量级的纯 Java Http 服务器的实现。下面是一个简单的例子:
public static void main(String[] args) throws Exception{
HttpServerProvider httpServerProvider = HttpServerProvider.provider();
InetSocketAddress addr = new InetSocketAddress(7778);
HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
httpServer.createContext("/myapp/", new MyHttpHandler());
httpServer.setExecutor(null);
httpServer.start();
System.out.println("started");
}
static class MyHttpHandler implements HttpHandler{
public void handle(HttpExchange httpExchange) throws IOException {
String response = "Hello world!";
httpExchange.sendResponseHeaders(200, response.length());
OutputStream out = httpExchange.getResponseBody();
out.write(response.getBytes());
out.close();
}
}
然后,在浏览器中访问 http://localhost:7778/myapp/
‘玖’ 怎么用java程序实现上传文件到指定的URL地址
//保存图片
privatevoidsaveImg(HttpServletRequestrequest,FormFileimgFile,FileFormfileForm){
if(imgFile!=null&&imgFile.getFileSize()>0){
StringfileName=imgFile.getFileName();
StringsqlPath="img/"+fileName;
//图片所在路径
StringsavePath=request.getSession().getServletContext().getRealPath("/")+"img\"+fileName;
System.out.println(fileName);
System.out.println(sqlPath);
System.out.println(savePath);
HttpSessionsession=request.getSession();
session.setAttribute("savePath",savePath);
session.setMaxInactiveInterval(60*60);
//StringsavePath1=(String)session.getAttribute("savePath");
//数据库
fileForm.getFile().setFileEmpPhoto(sqlPath);
//文件
try{
InputStreaminput=imgFile.getInputStream();
FileOutputStreamoutput=newFileOutputStream(savePath);
byte[]b=newbyte[1024];
while(input.read(b)!=-1){
output.write(b);
b=newbyte[1024];
}
output.close();
input.close();
}catch(FileNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
‘拾’ Java利用HttpURLConnection发送post请求上传文件
在页面里实现上传文件不是什么难事 写个form 加上enctype = multipart/form data 在写个接收的就可以了 没租裤什么难的 如果要用 HttpURLConnection来实现文件上传 还真有点搞头 : )
先写个servlet把接收到的 HTTP 信息保存在一个文件中 看一下 form 表单到底封装了什么样的信息
Java代码
public void doPost(HttpServletRequest request HttpServletResponse response)
throws ServletException IOException {
//获取输入流 是HTTP协议中的实体内容
ServletInputStream in=request getInputStream();
//缓冲区
byte buffer[]=new byte[ ];
FileOutputStream out=new FileOutputStream( d:\test log );
int len=sis read(buffer );
//把流里的信息循环读入到file log文件中
while( len!= ){
out write(buffer len);
len=in readLine(buffer );
}
out close();
in close();
}
来一个form表单
<form name= upform action= upload do method= POST
enctype= multipart/form data >
参数<input type= text name= username /><br/>
文件 <input type= file name= file /><br/>
文件 <input type= file name= file /><br/>
<input type= submit value= Submit />
<br />
</form>
假如我参数写的内容是hello word 然后二个文件是二个简单的txt文件梁誉 上传后test log里如下
Java代码
da e c
Content Disposition: form data; name= username
hello word
da e c
Content Disposition: form data; name= file ; filename= D:haha txt
Content Type: text/plain
haha
hahaha
da e c
Content Disposition: form data; name= file ; filename= D:huhu txt
Content Type: text/plain
messi
huhu
da e c
研究下规律发现有如下几点特征
第一行是 d b bc 作为分隔符 然后是 回车换行符 这个 d b bc 分隔符浏览器是随机生成的
第二行是Content Disposition: form data; name= file ; filename= D:huhu txt ;name=对应input的name值 filename对应要上传的文件名(包括路径在内)
第三行如果是文件就有Content Type: text/plain 这里上传的是txt文件所以是text/plain 如果上穿的是jpg图片的话就是image/jpg了 可以自己试试看看
然后就是回弊渣简车换行符
在下就是文件或参数的内容或值了 如 hello word
最后一行是 da e c 注意最后多了二个 ;
有了这些就可以使用HttpURLConnection来实现上传文件功能了
Java代码 public void upload(){
List<String> list = new ArrayList<String>(); //要上传的文件名 如 d:haha doc 你要实现自己的业务 我这里就是一个空list
try {
String BOUNDARY = d a d c ; // 定义数据分隔线
URL url = new URL( );
HttpURLConnection conn = (HttpURLConnection) url openConnection();
// 发送POST请求必须设置如下两行
conn setDoOutput(true);
conn setDoInput(true);
conn setUseCaches(false);
conn setRequestMethod( POST );
conn setRequestProperty( connection Keep Alive );
conn setRequestProperty( user agent Mozilla/ (patible; MSIE ; Windows NT ; SV ) );
conn setRequestProperty( Charsert UTF );
conn setRequestProperty( Content Type multipart/form data; boundary= + BOUNDARY);
OutputStream out = new DataOutputStream(conn getOutputStream());
byte[] end_data = ( + BOUNDARY + ) getBytes();// 定义最后数据分隔线
int leng = list size();
for(int i= ;i<leng;i++){
String fname = list get(i);
File file = new File(fname);
StringBuilder *** = new StringBuilder();
*** append( );
*** append(BOUNDARY);
*** append( );
*** append( Content Disposition: form data;name= file +i+ ;filename= + file getName() + );
*** append( Content Type:application/octet stream );
byte[] data = *** toString() getBytes();
out write(data);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = ;
byte[] bufferOut = new byte[ ];
while ((bytes = in read(bufferOut)) != ) {
out write(bufferOut bytes);
}
out write( getBytes()); //多个文件时 二个文件之间加入这个
in close();
}
out write(end_data);
out flush();
out close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn getInputStream()));
String line = null;
while ((line = reader readLine()) != null) {
System out println(line);
}
} catch (Exception e) {
System out println( 发送POST请求出现异常! + e);
e printStackTrace();
}
lishixin/Article/program/Java/hx/201311/27114