使用 HTTPHandler 上传文件 [英] File Upload using HTTPHandler
本文介绍了使用 HTTPHandler 上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 HTTPHandler 上传文件(多部分表单数据).
WebKit 边界正在写入目标文件,从而损坏文件.
输入文件可以是任何类型的文件,包括文本、zip、apk 等
代码:
public void handle(HttpExchange httpExchange) 抛出 IOException {URI uri = httpExchange.getRequestURI();String httpReqMethod = httpExchange.getRequestMethod();标头标头 = httpExchange.getRequestHeaders();InputStream inputStrm = null;FileOutputStream destFile = null;String contentType = ((headers.get("Content-type") != null) ? (headers.get("Content-type").toString()) : (null));httpExchange.getRequestURI().getQuery());映射<字符串,字符串>queryParams = queryToMap(httpExchange.getRequestURI().getQuery());设置<字符串>键= headers.keySet();迭代器<字符串>itr = keys.iterator();而(itr.hasNext()){String key = (String)itr.next();}File file = new File(ACEConstants.WEB_SERVER_CTX_ROOT + uri.getPath()).getCanonicalFile();字符串资源 = uri.getPath().substring(uri.getPath().indexOf(ACEConstants.WEB_SERVER_CTX_ROOT)+ACEConstants.WEB_SERVER_CTX_ROOT.length()+1);if(httpReqMethod.equals(ACEConstants.HTTP_REQUEST_METHOD_POST)){if(contentType != null && contentType.contains("multipart/form-data")){if(resource.equals("fileUpload")){inputStrm = httpExchange.getRequestBody();destFile = new FileOutputStream(new File("D:\"+queryParams.get("fileName")));String contentLength = headers.get("Content-length").toString();long fileSize = (Long.parseLong(contentLength.substring(1, contentLength.length()-1)));整数迭代 = 1;long bytesToBeRead = (fileSize > 1024) ?((iteration * 1024)) : (inputStrm.available());long bytesRemaining = (fileSize) - (iteration * 1024);字节[]字节=新字节[1024];如果(文件大小 <= 1024){字节 = 新字节[inputStrm.available()];inputStrm.read(bytes);destFile.write(bytes);}别的 {while (inputStrm.read(bytes) != -1) {迭代++;destFile.write(bytes);bytesRemaining = ( fileSize - ((iteration-1) * 1024));如果(剩余字节数 >= 1024){bytesToBeRead = 1024;字节=新字节[1024];}别的 {字节 = 新字节[inputStrm.available()];inputStrm.read(bytes);destFile.write(bytes);休息;}}}destFile.close();}}}}
这是 HTML 代码
<head lang="en"><meta charset="UTF-8"><title></title><script type="text/javascript">函数 processForm(frm){var fu1 = document.getElementsByName("数据文件");var 文件名 = fu1[0].value;filename = filename.substring(filename.lastIndexOf("\")+1);alert("您选择了" + 文件名);frm.action = "http://localhost:64444/ACE/fileUpload?fileName="+filename;返回真;}头部><身体><form name="myForm" enctype="multipart/form-data" method="post" acceptcharset="UTF-8" onsubmit="processForm(this);"><p>请指定一个文件或一组文件:
<input type="file" name="datafile" size="40"></p><div><输入类型=提交"值=发送">
</表单>