Post date: Sep 23, 2015 11:57:00 AM
node.jsの入れ方はこっち
やっぱり無理矢理でもjavaで書きたいなと思った.
Java
調べてみると,ApacheのHttpComponentsを使うと良いらしい.
public class FileSender { public static void main(String[] args) { System.out.println("fileTranslate:"+send(new File("data.png"),"http://localhost:3000/upload")); } public static String send(File file,String url){ String res=null; CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(url); httppost.setHeader("filename",file.getName()); FileBody bin = new FileBody(file); StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("file", bin) .addPart("comment", comment) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); res=response.getStatusLine().toString(); System.out.println(res); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } return "error"; }catch(Exception e){ try { httpclient.close(); } catch (IOException e1) { e1.printStackTrace(); } } return res; } }
Node.js
こっちも普通にmulterを使う.
入れ方はnpm i multer --saveとからしい
routeに次を記入する
var java = require('../controllers/javaClient.js'); router.post('/upload', multer({ dest: 'public/uploads/'}).single('file'), java.upload);
ここでjavaの.addPart("file", bin)とNode.jsの.single('file')の文字列は一致してないと500 internal server errorが帰ってくるので注意.