[英]SyntaxError: Unexpected token < in JSON at position 3 Angular2 with Servlet
I am uploading a file in angular2 front end and receiving it in a Servlet . 我正在angular2前端上传文件,并在Servlet中接收它。 The file passes to the backend but in the browser I am getting an error in the browser console at the subscribe observable .
该文件传递到后端,但是在浏览器中,我在浏览器控制台中看到了一个错误,位于subscribe observable。
AppComponent AppComponent
fileChange(event) {
const fileList: FileList = event.target.files;
if (fileList.length > 0) {
const file: File = fileList[0];
const formData: FormData = new FormData();
formData.append('uploadF', file, file.name);
const headers = new Headers();
/** No need to include Content-Type in Angular 4 */
// headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'text/html');
const options = new RequestOptions({ headers: headers });
// console.log('Reached here');
this.http.post(`http://localhost:8080/ProjSecond/Uploader1`, formData, options)
.map((res) => {console.log(res.json()); })
.catch(error => Observable.throw(error))
.subscribe(
resp => console.log('success' + resp),
error => console.log('error IS*&*&*&**' + error), // THIS LINE SHOWS ERROR
() => console.log('Operation Completed')
);
Servlet is : Servlet是:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
String oName = null;
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File("E:\\uploads\\" + name));
System.out.println("filename: " + name);
oName = name ;
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
request.setAttribute("fileName" , oName);
//response.sendRedirect("/result.jsp");
/* RequestDispatcher requestDispatcher;
requestDispatcher = request.getRequestDispatcher("/result.jsp");
requestDispatcher.forward(request, response);*/
request.getRequestDispatcher("http://localhost:4200/").forward(request, response);
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
What's wrong in the code ? 代码有什么问题? Thanks .
谢谢 。
Well I figured it out . 好吧,我想通了。 Angular always takes JSON as inputs from other applications(as per my research , please correct me if I am wrong).
Angular始终将JSON作为其他应用程序的输入(根据我的研究,如果我错了,请纠正我)。 Hence all I had to do was provide the string data as JSON from my Servlet .
因此,我要做的就是从Servlet提供字符串数据作为JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.