我希望有一个文件上传表单,除了文件选择输入之外,还具有其他输入字段,如文本区域、下拉列表等。问题是我无法访问除 blobstore 上传处理程序中的文件之外的任何发布参数。我使用以下函数调用来获取参数名称,但它始终返回空屏幕。
par = self.request.get("par")
我发现另一个问题有类似的问题将视频上传到 Google App Engine Blobstore https://stackoverflow.com/questions/3409375/uploading-a-video-to-google-app-engine-blobstore。该问题的答案提出了一种解决方案,将文件名设置为您希望读取的参数,但这不足以满足我的需求。有没有办法在 blobstore 上传处理程序的 post 方法中访问其他表单参数?
你找到解决办法了吗?
根据我的经验,当使用表单/多部分请求时,不包含其他参数,必须手动挖掘它们。
这就是我从用于发送文件的请求中挖掘出参数的方法。
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;
}
}
我希望这个快速答复对您有所帮助,如果您有疑问,请告诉我。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)