我正在尝试将图像从安卓发送到节点服务器。我做了什么:
try{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name="image_upload";originalFilename="" + params[1] + "";path="" + params[0] + """ + lineEnd); // originalFilename is the Name of the File to be uploaded
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
}
我在节点中获取image_upload
文件参数作为files.image_upload[0].originalFilename
和files.image_upload[0].path
问题发生在image_upload[0]
。服务器崩溃说 TypeError: Cannot read property '0' of undefined
为图像路径文件指定 mime 类型。
替换了一部分代码,它现在可以工作了。
dos.writeBytes("Content-Disposition: form-data; name="image_upload"; filename=""+params[1]+"""+lineEnd);
dos.writeBytes("Content-Type: "undefined""+lineEnd);
dos.writeBytes(lineEnd);