我只想尝试从android内部将位图上传到服务器。
我用Google搜索了一些内容并提出了这个问题,它实际上与另一个帖子完全相同,但它并不起作用。我不确定出了什么问题。从我的调试开始,当我做dos.flush()时,我得到一个" java.net.SocketException:sendto failed:EPIPE(Broken pipe)"我不明白为什么。
这是我的安卓代码
class upload extends AsyncTask<Bitmap, Void, String>{
@Override
protected String doInBackground(Bitmap... params) {
String attachmentName = "bitmap";
String attachmentFileName = "bitmap.bmp";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
HttpURLConnection huc = null;
URL url = new URL("http://dontenvy.me:5000/");
huc = (HttpURLConnection) url.openConnection();
huc.setChunkedStreamingMode(0);
huc.setDoOutput(true);
huc.setRequestMethod("POST");
huc.setRequestProperty("Connection", "Keep-Alive");
huc.setRequestProperty("Content-type", "multipart/form-data; boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(huc.getOutputStream());
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\"; filename=\"" + attachmentFileName + "\"" + crlf);
dos.writeBytes(crlf);
Bitmap small = Bitmap.createScaledBitmap(params[0], 100, 100, false);
byte[] pixels = new byte[small.getWidth() * small.getHeight()];
for (int i = 0; i < small.getWidth(); ++i) {
for (int j = 0; j < small.getHeight(); ++j) {
//we're interested only in the MSB of the first byte,
//since the other 3 bytes are identical for B&W images
pixels[i + j] = (byte) ((small.getPixel(i, j) & 0x80) >> 7);
}
}
dos.write(pixels);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
dos.flush();
dos.close();
huc.disconnect();
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return null //once i get this working I'll do a response code return
}
}
这是我的服务器端代码。我只是使用烧瓶,因为我觉得它最容易
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
UPLOAD_FOLDER = "/home/luisfmh/vigeo/uploads"
ALLOWED_EXTENSIONS = set(["png", "jpg", "bmp"])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS
@app.route("/", methods=["GET", "POST"])
def upload_file():
print len(request.files)
if request.method == "POST":
file = request.files["bitmap"]
if file: ##and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
return '''success!!'''
return '''
<!doctype html>
<title> Upload new File</title>
<h1> Upload new file</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
if __name__ == "__main__":
app.run(debug=True, host = "0.0.0.0" )