用java实现上传文件

html文件上传:

html部分界面:

<form action="http://localhost:8080/hub/container/addContainer" method="post" enctype="multipart/form-data">
war包:<input type="file" name="attach" id="attach" size="50" >
<input type="submit" value="提交">
</form>                                              												


/**
	 * 接收从客户端上传的文件,并保存在本地
	 */
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
。。。
	private String uploadFile() {
		String newFileName="";
		try {
			String MsgFilesURL_PATH = "";
			MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
			// 获得未见过滤器
			File file = wrapper.getFiles("attach")[0];
			// 获得上传的文件名
			String fileName = wrapper.getFileNames("attach")[0];
			// ----------重新构建上传文件名---------
			final Lock lock = new ReentrantLock();
			String newName = null;
			lock.lock();
			try {
				// 加锁为防止文件名重复
				SimpleDateFormat formatter = new SimpleDateFormat(
						"yyyyMMddHHmmss");
				newName = formatter.format(new Date()) + fileName;
			} finally {
				lock.unlock();
			}
			// ------锁结束---------
			// 获取文件输出流
				newFileName=request.getSession().getServletContext().getRealPath("/")
					+ MsgFilesURL_PATH + newName;
			FileOutputStream fos = new FileOutputStream(newFileName);
			// 获取内存中当前文件输入流
			InputStream in = new FileInputStream(file);
			try {
				int len = in.available();
				byte[] buffer = new byte[len];
				in.read(buffer);
				fos.write(buffer);
			} catch (Exception e) {
				e.printStackTrace(System.err);
			} finally {
				in.close();
				fos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newFileName;
	}

//模拟浏览器提交表单数据,上传文件
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
。。。
	private int postFile(String URLString, String filePath,String json) {
		   File targetFile = new File(filePath);
		   PostMethod filePost = new PostMethod(URLString);
		   try
		   {
		    //通过以下方法可以模拟页面参数提交
		    Part[] parts = {new StringPart("json", json), new FilePart("attach", targetFile) };
		    filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
		    HttpClient client = new HttpClient();
		    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		    int status = client.executeMethod(filePost);
			    if (status == HttpStatus.SC_OK){
			    	return 0;//上传成功
			    }else{
			      
			    	return -1;//上传失败
			    }
		   }
		   catch (Exception ex){
		     return -1;
		   }
		   finally{
		     filePost.releaseConnection();
		   }
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值