我使用Android和nodejs express。我想上传图片到快递服务器。
我正在使用翻新版,并且想要在服务器中另存为multer。
我认为req.files应该有东西可以使用multer ...
我该怎么办..?
这是我的Android改装代码。
@Multipart
@POST("/upload")
Call<UploadObject> uploadFile(@Part MultipartBody.Part file, @Part("name") RequestBody name);
public class Main2Activity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
private static final String TAG = "UPLOAD";
private static final int REQUEST_GALLERY_CODE = 200;
private static final int READ_REQUEST_CODE = 300;
private static final String SERVER_PATH = "http://52.231.67.203:3000";
private Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button selectUploadButton = (Button)findViewById(R.id.select_image);
selectUploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK);
openGalleryIntent.setType("image/*");
startActivityForResult(openGalleryIntent, REQUEST_GALLERY_CODE);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, Main2Activity.this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_GALLERY_CODE && resultCode == Activity.RESULT_OK){
uri = data.getData();
if(EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
String filePath = getRealPathFromURIPath(uri, Main2Activity.this);
File file = new File(filePath);
Log.d(TAG, "Filename " + file.getName());
//RequestBody mFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), mFile);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_PATH)
.addConverterFactory(GsonConverterFactory.create())
.build();
HttpInterface uploadImage = retrofit.create(HttpInterface.class);
Call<UploadObject> fileUpload = uploadImage.uploadFile(fileToUpload, filename);
fileUpload.enqueue(new Callback<UploadObject>() {
@Override
public void onResponse(Call<UploadObject> call, Response<UploadObject> response) {
Toast.makeText(Main2Activity.this, "Response " + response.raw().message(), Toast.LENGTH_LONG).show();
Toast.makeText(Main2Activity.this, "Success " + response.body().getSuccess(), Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<UploadObject> call, Throwable t) {
Log.d(TAG, "Error " + t.getMessage());
}
});
}else{
EasyPermissions.requestPermissions(this, getString(R.string.read_file), READ_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
}
private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
if(uri != null){
String filePath = getRealPathFromURIPath(uri, Main2Activity.this);
File file = new File(filePath);
RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), mFile);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_PATH)
.addConverterFactory(GsonConverterFactory.create())
.build();
HttpInterface uploadImage = retrofit.create(HttpInterface.class);
Call<UploadObject> fileUpload = uploadImage.uploadFile(fileToUpload, filename);
fileUpload.enqueue(new Callback<UploadObject>() {
@Override
public void onResponse(Call<UploadObject> call, Response<UploadObject> response) {
Toast.makeText(Main2Activity.this, "Success " + response.message(), Toast.LENGTH_LONG).show();
Toast.makeText(Main2Activity.this, "Success " + response.body().toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<UploadObject> call, Throwable t) {
Log.d(TAG, "Error " + t.getMessage());
}
});
}
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
Log.d(TAG, "Permission has been denied");
}
}
和服务器app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var fs = require('fs');
// const mongoose = require('mongoose');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var contentsRouter = require('./routes/contents');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/contents', contentsRouter);
app.post('/upload', function(req, res) {
console.log(req.files)
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;