英文:
Looking for a way to use ajax to upload a file to a appengine go server using angularjs
问题
服务器代码:
func addImageHandler(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
blobs, _, err := blobstore.ParseUpload(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file := blobs["file"]
....
}
我成功地访问了处理程序,但是当我解析上传时,在我的blobs映射中没有任何文件。我是否遗漏了一些明显的东西?
谢谢!
英文:
Javascript code:
$http({
method: 'POST',
url: 'some/path',
headers: { 'Content-Type': false },
transformRequest: function (data) {
var formData = new FormData();
formData.append("file", data);
return formData;
},
data: file
}).
success(function (data, status, headers, config) {
alert("success!");
}).
error(function (data, status, headers, config) {
alert("failed!");
});
Server code:
func addImageHandler(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
blobs, _, err := blobstore.ParseUpload(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file := blobs["file"]
....
}
I'm hitting the handler just fine but when i parse the upload I don't have any files in my blobs map. Is there something obvious i'm missing?
Thanks!
答案1
得分: 0
似乎你的Content-Type是错误的,应该是multipart-form等等。
headers: { 'Content-Type': false },
确保表单有一个Field类型,例如:
<input type="file" />
最后确保
len(blobs["file"]) != 0
如果是这样的话,很可能意味着浏览器没有以正确的格式发送数据,appengine无法识别。使用Chrome开发者工具检查ajax调用试图发送的内容。
这是一个很好的用于上传数据的angularjs小部件的fiddle链接:http://jsfiddle.net/CPsRs/
英文:
Seems like your Content-Type is wrong, it should be multipart-form etc.
headers: { 'Content-Type': false },
Make sure the form has a Field type like:
<input type="file" />
Finally make sure that
len(blobs["file"]) != 0
If it is then it most likely means that the browser is not sending the data in the right format and appengine is not recognizing it. Use Chrome developer tools to inspect what is the ajax call trying to send.
This is a fiddle for a nice angularjs widget to upload data: http://jsfiddle.net/CPsRs/
答案2
得分: 0
问题的原因是原始问题中没有包含的一个细节。你需要确保你正在使用blobstore来生成上传URL。例如:
func ServeUploadUrl(w http.ResponseWriter, request *http.Request) {
context := appengine.NewContext(request)
myUrl := "some/upload/url"
// 在这里创建blobstore的URL
blobstore.UploadURL(context, myUrl, nil)
...
}
英文:
The problem has turned out to be a detail that wasn't included in the original question. You need to ensure that you're using the blobstore to generate the upload url. For example:
func ServeUploadUrl(w http.ResponseWriter, request *http.Request) {
context := appengine.NewContext(request)
myUrl := "some/upload/url"
// create the blobstore url here
blobstore.UploadURL(context, myUrl, nil)
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论