我希望有一个文件上传表单,除了文件选择输入外,还有其他输入字段,如textarea,dropdown等。问题是我无法访问除blobstore上传处理程序中的文件以外的任何帖子参数。我正在使用以下函数调用来获取参数名称,但它总是返回一个空屏幕。
par = self.request.get(“par”)
我发现了另一个类似问题Uploading a video to google app engine blobstore的问题。该问题的答案提出了一种解决方法,可以将文件名设置为您想要读取的参数,但这并不足以满足我的需求。有没有办法在blobstore上传处理程序的post方法中访问其他表单参数?
答案 0 :(得分:1)
您找到了解决方案吗?
根据我的经验,当使用表单/多部分请求时,不包括其他参数,必须手动挖出它们。
这就是我从用于发送文件的请求中挖出参数的方法。
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
// for reading form data when posted with multipart/form-data
import java.io.*;
import javax.servlet.ServletException;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.google.appengine.api.datastore.Blob;
// Fetch the attributes for a given model using rails conventions.
// We need to do this in Java because getParameterMap uses generics.
// We currently only support one lever: foo[bar] but not foo[bar][baz].
// We currently only pull the first value, so no support for checkboxes
public class ScopedParameterMap {
public static Map params(HttpServletRequest req, String model)
throws ServletException, IOException {
Map<String, Object> scoped = new HashMap<String, Object>();
if (req.getHeader("Content-Type").startsWith("multipart/form-data")) {
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req); // this is used to get those params
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
String attr = item.getFieldName();
if (attr.startsWith(model + "[") && attr.endsWith("]")) { // fetches all stuff like article[...], you can modify this to return only one value
int len = 0;
int offset = 0;
byte[] buffer = new byte[8192];
ByteArrayOutputStream file = new ByteArrayOutputStream();
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
offset += len;
file.write(buffer, 0, len);
}
String key = attr.split("\\[|\\]")[1];
if (item.isFormField()) {
scoped.put(key, file.toString());
} else {
if (file.size() > 0) {
scoped.put(key, file.toByteArray());
}
}
}
}
} catch (Exception ex) {
throw new ServletException(ex);
}
} else {
Map params = req.getParameterMap();
Iterator i = params.keySet().iterator();
while (i.hasNext()) {
String attr = (String) i.next();
if (attr.startsWith(model + "[") && attr.endsWith("]")) {
String key = attr.split("\\[|\\]")[1];
String val = ((String[]) params.get(attr))[0];
scoped.put(key, val);
// TODO: when multiple values, set a List instead
}
}
}
return scoped;
}
}
我希望这个快速的答案有所帮助,如果您有疑问,请告诉我。