java+express+multiparty上传文件到服务器测试
来源:互联网 发布:maya动画导入unity3d 编辑:程序博客网 时间:2024/06/05 05:38
server:
app.get('/',function(req, res) { res.send("<form method='post', action='/file/uploading', enctype='multipart/form-data'><input name='inputFile', type='file', multiple='mutiple'><input name='btnUp', type='submit',value='上传'></form>");});app.post('/file/uploading', function(req, res, next){ var form = new multiparty.Form({uploadDir: currPath+'public/'}); form.parse(req, function(err, fields, files) { var filesTmp = JSON.stringify(files,null,2); if(err){ console.log('parse error: ' + err); } else { console.log('parse files: ' + filesTmp); var inputFile = files.inputFile[0]; var uploadedPath = inputFile.path; var dstPath = currPath+'public/' + inputFile.originalFilename; //重命名为真实文件名 fs.rename(uploadedPath, dstPath, function(err) { if(err){ console.log('rename error: ' + err); } else { console.log('rename ok'); } }); } res.writeHead(200, {'content-type': 'text/plain;charset=utf-8'}); res.write('received upload:\n\n'); res.end(util.inspect({fields: fields, files: filesTmp})); }); });java:
public class UploadFileTest { public void start() throws Exception { String serverUrl = "http://xxxxxxxx:xxx/file/uploading";//上传地址 ArrayList<FormFieldKeyValuePair> ffkvp = new ArrayList<FormFieldKeyValuePair>(); ffkvp.add(new FormFieldKeyValuePair("type", "txt")); ArrayList<UploadFileItem> ufi = new ArrayList<UploadFileItem>(); ufi.add(new UploadFileItem("inputFile", "D:\\123.txt")); uploadLog hpe = new uploadLog(); String response = hpe.sendHttpPostRequest(serverUrl, ffkvp, ufi); System.out.println("Responsefrom server is: " + response); }} class uploadLog {private static final String BOUNDARY = "----------HV2ymHFg03ehbqgZCaKO6jyH"; public String sendHttpPostRequest(String serverUrl, ArrayList<FormFieldKeyValuePair> generalFormFields, ArrayList<UploadFileItem> filesToBeUploaded) throws Exception { URL url = new URL(serverUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 发送POST请求必须设置如下两行 connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Charset", "UTF-8"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); StringBuffer contentBody = new StringBuffer("--" + BOUNDARY); String endBoundary = "\r\n--" + BOUNDARY + "--\r\n"; OutputStream out = connection.getOutputStream(); for (FormFieldKeyValuePair ffkvp : generalFormFields) { contentBody.append("\r\n") .append("Content-Disposition: form-data; name=\"") .append(ffkvp.getKey() + "\"") .append("\r\n") .append("\r\n") .append(ffkvp.getValue()) .append("\r\n") .append("--") .append(BOUNDARY); } String boundaryMessage1 = contentBody.toString(); out.write(boundaryMessage1.getBytes("utf-8")); for (UploadFileItem ufi : filesToBeUploaded) { contentBody = new StringBuffer(); contentBody.append("\r\n") .append("Content-Disposition:form-data; name=\"") .append(ufi.getFormFieldName() + "\"; ") // form中field的名称 .append("filename=\"") .append(ufi.getFileName() + "\"") // 上传文件的文件名,包括目录 .append("\r\n") .append("Content-Type:text/plain") .append("\r\n\r\n"); String boundaryMessage2 = contentBody.toString(); out.write(boundaryMessage2.getBytes("utf-8")); File file = new File(ufi.getFileName()); DataInputStream dis = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[(int) file.length()]; bytes = dis.read(bufferOut); out.write(bufferOut, 0, bytes); dis.close(); } out.write(endBoundary.getBytes("utf-8")); out.flush(); out.close(); String strLine = ""; String strResponse = ""; InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); while ((strLine = reader.readLine()) != null) { strResponse += strLine + "\n"; } return strResponse; } }class FormFieldKeyValuePair { private static final long serialVersionUID = 1L; //The form field used for receivinguser's input, // such as "username" in "<input type="text" name="username"/>" private String key; //The value entered by user in thecorresponding form field, // such as "Patrick" the abovementioned formfield "username" private String value; public FormFieldKeyValuePair(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } class UploadFileItem implements Serializable{ private static final long serialVersionUID = 1L; //The form field name in a form used foruploading a file, // such as "upload1" in "<input type="file" name="upload1"/>" private String formFieldName; //File name to be uploaded, thefileName contains path, // such as "E:\\some_file.jpg" private String fileName; public UploadFileItem(String formFieldName, String fileName) { this.formFieldName = formFieldName; this.fileName = fileName; } public String getFormFieldName() { return formFieldName; } public void setFormFieldName(String formFieldName) { this.formFieldName = formFieldName; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
阅读全文
0 0
- java+express+multiparty上传文件到服务器测试
- nodejs后台文件上传模块connect-multiparty
- multiparty node.js的中间件 --- 上传文件
- Java文件上传到服务器
- java上传文件到服务器
- Java上传文件到服务器
- nodejs使用connect-multiparty实现文件上传(文件接收)后端
- node.js 上传东西到服务器 express
- 服务器fastdfs java 文件上传测试
- java FTP上传文件到服务器
- java servlet 上传文件到服务器
- java上传文件到FTP服务器
- java之TCP上传文件到服务器
- java上传文件与文件夹到服务器
- IOS上传文件到JAVA服务器
- java将文件上传到ftp服务器
- java 实现上传文件到远程服务器
- Java 上传文件到ftp服务器
- 用74HC165读8个按键状态
- 遍历map
- 线性代数(蜜汁数学)
- 《从零开始搭建游戏服务器》 网络数据压缩——Zlib算法
- Python安装lxml找不到etree
- java+express+multiparty上传文件到服务器测试
- 简单并查集Wireless Network POJ
- c3p0在javaApp项目中的操作
- java上传文件到远程服务器(二)---HttpClient方式
- unity 贴图材质的调整-uv通道修改
- css sprites-简单实例让你快速掌握css sprites精髓
- Myeclipse tomcat部署好project之后,点finish无效
- Oracle SQL实现分页查询
- general error c101008a: Failed to save the updated manifest to the file