[英]Can't upload picture to web server
我創建了兩個項目,一個用於客戶端,一個用於服務器端。 似乎沒有用。 我認為這可能與POST請求與Web表單的文件格式不匹配有關。 我想將圖片發送到Web服務器。 首先,我想從我的計算機上進行此操作,將來希望通過Android手機進行。 這是我得到的代碼:
客戶端:
public class Send {
public static void main(String[] args) throws Exception {
String filePath = "C:\\Users\\Mat\\Desktop\\Pic.bmp";
String picName = "Pic.bmp";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/springmvc/upload");
FileBody pic = new FileBody(new File(filePath));
StringBody name = new StringBody(picName);
MultipartEntity requestEntity = new MultipartEntity();
requestEntity.addPart("text", name);
requestEntity.addPart("file", pic);
httppost.setEntity(requestEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (responseEntity != null) {
System.out.println("Response content length: " + responseEntity.getContentLength());
}
EntityUtils.consume(responseEntity);
} finally {
try {
httpclient.getConnectionManager().shutdown();
}
catch (Exception ignore) {
}
}
}
}
來自“ System.out.println(response.getStatusLine());” 我得到輸出“ HTTP / 1.1 400 Bad Request”
服務器端(Web服務器):
控制器:
@Controller
public class HomeController {@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws IOException {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
FileOutputStream fos = new FileOutputStream(
"C:\\Users\\Mat\\Desktop\\image.bmp");
try {
fos.write(bytes);
} finally {
fos.close();
}
return "works";
} else {
return "doesn't work";
}
}
}
.jsp文件(我認為是表單):
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="/form" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
豆子:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
<!-- Declare explicitly, or use <context:annotation-config/> -->
<bean id="HomeController" class="net.codejava.springmvc.HomeController">
</bean>
增加了依賴性(我從MVC模板創建了一個項目,因此從一開始就有很多):
<!-- UploadImage -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
我希望客戶端發送帶有特定名稱的圖片,而無需從客戶端進行任何手動工作。
我正在使用STS和Spring MVC框架。
如果有人看到我在做什么錯,我將不勝感激!
預先感謝!
問題在於該表格應為:
<input type="text" name="name"/>
當我刪除該行時,它起作用了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.