我正在尝试将单个图像上传到具有多个字符串的节点js服务器。到目前为止,我的代码将图像作为POST变量发送到服务器,即在 req.body 中。而Node JS中的multer在 req.file 中查找图像。因此,我无法上传图像并继续获得402代理错误。
Android代码
// String Parameters
Map<String, String> params = new HashMap<String, String>();
params.put("title", title_text);
params.put("description", description_text);
params.put("location", location_text);
myServerRequest.multipartRequest(
URL,
myServerRequest.getImageByte(selectedImageForUpload),
params,
new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse networkResponse) {
Toast.makeText(PostUpload.this, networkResponse.toString(), Toast.LENGTH_LONG).show();
Log.i("Post UPload", networkResponse.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley Error FOund", "Error: " + error
+ ">>" + error.networkResponse.statusCode
+ ">>" + new String(error.networkResponse.data)
+ ">>" + error.networkResponse.headers.toString()
+ ">>" + error.getCause()
+ ">>" + error.getMessage());
}
}
);
多部分请求类的代码
public class MultipartRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
private final Map<String, String> mHeaders;
private final String mMimeType;
private final byte[] mMultipartBody;
public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] multipartBody, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
this.mHeaders = headers;
this.mMimeType = mimeType;
this.mMultipartBody = multipartBody;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
@Override
public String getBodyContentType() {
return mMimeType;
}
@Override
public byte[] getBody() throws AuthFailureError {
return mMultipartBody;
}
@Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
@Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
myServerRequest类函数
public static void multipartRequest(final String url, byte[] file, Map<String, String> params, Response.Listener<NetworkResponse> success, Response.ErrorListener error) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// the image file
buildPart(dos, file, "avatar");
// the string params
for (Map.Entry<String, String> entry : params.entrySet()) {
//System.out.println(entry.getKey() + "/" + entry.getValue());
buildTextPart(dos, entry.getKey(), entry.getValue());
}
// send multipart form data necesssary after file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// pass to multipart body
multipartBody = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
MultipartRequest multipartRequest = new MultipartRequest(url, null, mimeType, multipartBody, success, error);
MyVolleyRequest.getInstance(Main.getAppContext()).addToRequestQueue(multipartRequest);
}
private static void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"" + lineEnd);
dataOutputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(parameterValue + lineEnd);
}
private static void buildPart(DataOutputStream dataOutputStream, byte[] fileData, String fileName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"avtar\"; filename=\""
+ fileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(fileData);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
}
节点JS代码
router.post('/upload', upload.single('avatar'), function(req, res) {
db.uploadPost(req, 1, function(image) {
response = {};
// Rectify un-useful
if(image.error) {
response.success = false;
response.error = image.error;
response.data = image.data;
} else {
response.success = true;
response.name = req.file.filename;
response.thumb = image.name;
response.type = image.type;
//response.width = image.width;
//response.height = image.height;
}
res.json(response);
});
});
如何将头像从 req.body 移至 req.file ?
更新
添加了Multipart主体以进行请求。现在获得200但帖子仍然没有上传。 请求对象现在没有req.body或req.file。